Add new rector rule for SimplifyIfElseToTernaryRector#2666
Conversation
|
Warning Rate limit exceeded@Crabcyborg has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 23 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (3)
WalkthroughRefactors conditional expressions across ~60 files, replacing multi-line if/else blocks with ternary operators and null-coalescing expressions. No public API/signature changes or control-flow semantics were intentionally altered. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
classes/views/shared/mb_adv_info.php (1)
240-240: Refactoring is correct; consider line wrapping to comply with WordPress style guidelines.The ternary refactoring preserves logic correctly and uses
isset()to test the true condition, which aligns with WordPress standards. However, the resulting line is approximately 124 characters, exceeding the recommended 80-character soft limit. While this is a minor style consideration, wrapping the ternary across multiple lines could improve readability:$code = isset( $uid ) ? str_replace( '|user_id|', $uid, $code ) : str_replace( '|user_id|', 'x', $code );This is optional if your codebase has established a higher line-length threshold or does not enforce this WordPress guideline.
classes/models/FrmEntryFormatter.php (1)
202-204: Fix indentation and simplify boolean check.The ternary conversion is correct, but consider these improvements:
- Line 203 has inconsistent indentation (appears to use spaces instead of tabs).
- The comparison
=== trueis redundant sinceis_plain_textis already a boolean property.Apply this diff:
- } elseif ($atts['format'] === 'text') { - $this->format = $this->is_plain_text === true ? 'plain_text_block' : 'table'; - } + } elseif ( $atts['format'] === 'text' ) { + $this->format = $this->is_plain_text ? 'plain_text_block' : 'table'; + }classes/models/FrmInstallPlugin.php (1)
35-40: Ternary simplification inget_activate_linkpreserves behaviorThe new ternary correctly mirrors the prior if/else logic (installed+active → empty string; installed+inactive → activate URL; not installed → install URL). If you want, you could cache
$this->is_installed()in a local variable to avoid calling it twice, but that's optional.classes/controllers/FrmAddonsController.php (1)
803-813: Null-coalescing on$addon['file']slightly changesnullhandling
$base_file = $addon['file'] ?? 'formidable-' . $slug;is equivalent to the oldisset()check except when$addon['file']is present butnull. In that edge case, the code will now fall back to'formidable-' . $sluginstead of usingnull, which is probably safer but is a behavior change.If there are any addons that intentionally set
'file' => null, this could alter their resolved$file_name. Otherwise this is fine.If you want to keep the old semantics exactly, you could use:
$base_file = array_key_exists( 'file', $addon ) ? $addon['file'] : 'formidable-' . $slug;classes/helpers/FrmFieldsHelper.php (1)
2592-2619: Always-settingdata-oneclickmay impact consumers that rely on attribute absence
$install_data = isset( $upgrading['url'] ) ? wp_json_encode( $upgrading ) : '';meansdata-oneclickis now always added, but with an empty string when there’s no upgrade URL.Most code that checks
if ( $el.data('oneclick') )will still behave the same (empty string is falsy), but any JS that distinguishes between “no attribute” vs “empty attribute” via.attr('data-oneclick')or similar could see a change.If you want to keep the prior contract, you could skip emitting the attribute when there’s no URL:
if ( isset( $upgrading['url'] ) ) { $custom_attrs['data-oneclick'] = wp_json_encode( $upgrading ); } $custom_attrs['data-requires'] = FrmFormsHelper::get_plan_required( $upgrading );Please confirm how the front-end uses
data-oneclickbefore relying on the new behavior.classes/helpers/FrmAppHelper.php (2)
461-461: Consider extracting for readability.This ternary is dense with multiple operations. While functionally correct, consider extracting to improve clarity:
-$function = count( $value ) ? explode( ', ', FrmDb::prepare_array_values( $value, $function ) ) : array( $function ); +$prepared_values = count( $value ) ? FrmDb::prepare_array_values( $value, $function ) : $function; +$function = count( $value ) ? explode( ', ', $prepared_values ) : array( $function );Or add a brief comment explaining the placeholder generation logic.
3239-3239: Consider clarifying the empty-but-not-zero check.The condition
empty( $to ) && 0 !== $tois logically correct (preserving 0 as a valid timestamp) but not immediately intuitive. Consider adding a brief comment or extracting to a named variable:-$now = empty( $to ) && 0 !== $to ? new DateTime() : new DateTime( '@' . $to ); +// Use current time if $to is empty, but preserve 0 as valid Unix epoch timestamp +$now = empty( $to ) && 0 !== $to ? new DateTime() : new DateTime( '@' . $to );Alternatively:
$use_current_time = empty( $to ) && 0 !== $to; $now = $use_current_time ? new DateTime() : new DateTime( '@' . $to );
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (41)
classes/controllers/FrmAddonsController.php(1 hunks)classes/controllers/FrmAppController.php(1 hunks)classes/controllers/FrmXMLController.php(1 hunks)classes/factories/FrmFieldFactory.php(1 hunks)classes/helpers/FrmAppHelper.php(7 hunks)classes/helpers/FrmEmailSummaryHelper.php(1 hunks)classes/helpers/FrmEntriesHelper.php(2 hunks)classes/helpers/FrmEntriesListHelper.php(1 hunks)classes/helpers/FrmFieldsHelper.php(3 hunks)classes/helpers/FrmFormsHelper.php(6 hunks)classes/helpers/FrmFormsListHelper.php(1 hunks)classes/helpers/FrmListHelper.php(2 hunks)classes/helpers/FrmStylesHelper.php(1 hunks)classes/helpers/FrmXMLHelper.php(3 hunks)classes/models/FrmAddon.php(2 hunks)classes/models/FrmAntiSpam.php(1 hunks)classes/models/FrmEmail.php(1 hunks)classes/models/FrmEntry.php(3 hunks)classes/models/FrmEntryFormatter.php(2 hunks)classes/models/FrmEntryMeta.php(1 hunks)classes/models/FrmEntryValidate.php(1 hunks)classes/models/FrmEntryValues.php(1 hunks)classes/models/FrmField.php(4 hunks)classes/models/FrmFieldOption.php(1 hunks)classes/models/FrmForm.php(4 hunks)classes/models/FrmInstallPlugin.php(1 hunks)classes/models/FrmReviews.php(1 hunks)classes/models/FrmStyle.php(2 hunks)classes/models/fields/FrmFieldCaptcha.php(1 hunks)classes/models/fields/FrmFieldType.php(4 hunks)classes/models/fields/FrmFieldUserID.php(1 hunks)classes/views/frm-entries/_sidebar-shared-pub.php(1 hunks)classes/views/shared/admin-cta.php(1 hunks)classes/views/shared/mb_adv_info.php(1 hunks)rector.php(0 hunks)square/controllers/FrmSquareLiteEventsController.php(1 hunks)square/helpers/FrmSquareLiteConnectHelper.php(2 hunks)stripe/controllers/FrmStrpLiteEventsController.php(1 hunks)stripe/controllers/FrmTransLiteActionsController.php(2 hunks)stripe/helpers/FrmTransLiteListHelper.php(1 hunks)stripe/models/FrmStrpLiteAuth.php(1 hunks)
💤 Files with no reviewable changes (1)
- rector.php
🧰 Additional context used
🧬 Code graph analysis (7)
classes/models/FrmEntryFormatter.php (1)
classes/models/FrmEntry.php (2)
FrmEntry(6-1296)getOne(482-510)
classes/helpers/FrmAppHelper.php (1)
classes/models/FrmDb.php (2)
FrmDb(6-867)prepare_array_values(636-640)
classes/factories/FrmFieldFactory.php (1)
classes/models/fields/FrmFieldDefault.php (1)
FrmFieldDefault(9-70)
classes/models/FrmInstallPlugin.php (1)
classes/controllers/FrmAddonsController.php (1)
is_installed(620-623)
classes/models/FrmField.php (1)
classes/models/FrmDb.php (2)
FrmDb(6-867)get_var(247-261)
classes/models/FrmAddon.php (3)
classes/models/FrmFormApi.php (1)
transient_key(221-223)classes/models/FrmField.php (1)
get_option(1473-1475)classes/models/FrmForm.php (1)
get_option(1310-1315)
classes/helpers/FrmFormsHelper.php (1)
classes/helpers/FrmAppHelper.php (1)
current_user_can(2267-2289)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: PHP 8 tests in WP trunk
- GitHub Check: PHP 7.4 tests in WP trunk
- GitHub Check: Cypress
- GitHub Check: PHP 8 tests in WP trunk
- GitHub Check: PHP 7.4 tests in WP trunk
- GitHub Check: Cypress
🔇 Additional comments (50)
classes/models/fields/FrmFieldCaptcha.php (1)
30-35: Clean refactor—unnecessary variable removed.The inlining of the ternary expression directly into the return statement eliminates the intermediate
$image_namevariable while preserving the exact logic: return'recaptcha_v3'when active captcha is reCAPTCHA v3, otherwise return the active captcha type. The change is correct and improves readability.classes/helpers/FrmStylesHelper.php (1)
234-234: Clean refactor to ternary operator.The condition logic is preserved correctly:
0 === strpos( $color, 'rgb' )accurately identifies RGB-formatted color strings and routes to the appropriate parser. The ternary replacement improves readability without affecting functionality or behavior.stripe/controllers/FrmTransLiteActionsController.php (2)
267-267: LGTM! Clean ternary refactor.The conditional assignment is now more concise while preserving the original logic.
571-571: LGTM! Clean ternary refactor.The conditional assignment is now more concise while preserving the original logic and maintaining the strict comparison.
square/helpers/FrmSquareLiteConnectHelper.php (2)
52-58: LGTM!The PHP tag formatting change has no functional impact and maintains code clarity.
79-80: LGTM!The ternary conversion is clean and appropriate for this simple conditional assignment. The boolean cast ensures predictable evaluation, and readability is maintained.
stripe/controllers/FrmStrpLiteEventsController.php (1)
531-531: LGTM!The ternary refactor correctly implements the increment-or-initialize logic for the failure counter. The
is_int()check appropriately handles WordPress transient behavior (returnsfalsewhen absent), and the expression is concise and readable.stripe/models/FrmStrpLiteAuth.php (1)
740-740: LGTM! Clean ternary refactoring.The conversion to a ternary operator is appropriate here—the condition is simple, both branches return URLs, and
conf_methodis guaranteed to be set byprepare_success_atts. The refactoring maintains identical behavior while improving conciseness.square/controllers/FrmSquareLiteEventsController.php (1)
130-130: LGTM! Clean refactoring to ternary.The ternary expression correctly handles the failed event counter logic: incrementing if the transient exists as an integer, or initializing to 1 otherwise. The
is_int()check is appropriate sinceget_transient()returnsfalsewhen the transient doesn't exist.classes/models/FrmEntryValues.php (1)
181-183: No formatting changes needed. The code already follows WordPress coding standards with proper tab-based indentation, correct spacing around operators (if ( ! empty(...)), and properly aligned control structures.classes/models/FrmEntryMeta.php (1)
539-541: LGTM! Clean ternary refactoring.The conversion from if/else to a ternary operator is correct and maintains the original logic while improving code conciseness. The conditional handling of draft status based on class existence is clear.
classes/models/FrmEmail.php (1)
672-676: LGTM!The refactor from if/else to ternary is clean and maintains the original logic correctly. The expression concisely handles both array (splitting and trimming multiple emails) and scalar (trimming a single value) cases.
classes/controllers/FrmXMLController.php (1)
112-116: LGTM!The null coalescing operator correctly preserves the original if/else logic: use
$imported['error']if set, otherwise fall back to the default error message.classes/models/FrmFieldOption.php (1)
61-61: LGTM!The ternary expression correctly consolidates the option label logic. The nested null coalescing operator properly handles the case where
$this->option['label']is not set, falling back to the first array element viareset().classes/models/FrmAntiSpam.php (1)
59-59: LGTM!The ternary expression accurately preserves the original logic: if
$currentis not strictlytrue, use it as the timestamp; otherwise, usetime().classes/helpers/FrmListHelper.php (2)
767-767: LGTM!The ternary expression cleanly delegates to the appropriate helper method based on the
disabledflag.
963-965: LGTM!Both ternary expressions correctly handle the
orderbyandorderparameters:
- Line 963 safely checks
isset($_GET['orderby'])before sanitizing- Line 965 validates both existence and value of
$_GET['order']The loose comparison on line 965 (
'desc' == $_GET['order']) is appropriate for this use case.classes/views/shared/admin-cta.php (1)
15-15: LGTM!The ternary expression correctly uses strict comparison (
false === strpos(...)) to determine if'frm-gradient'is absent from the class string, then sets the appropriate button class.classes/models/FrmEntryValidate.php (1)
152-152: LGTM!The ternary with nested null coalescing operator properly handles the value extraction logic:
- When
parent_field_idis empty, safely accesses$values['item_meta'][$args['id']]with a fallback to empty string- Otherwise uses
$valuesdirectlystripe/helpers/FrmTransLiteListHelper.php (1)
140-140: LGTM!The ternary expression correctly sets the
class="current"attribute when the status matches the active transaction type, otherwise returns an empty string.classes/controllers/FrmAppController.php (1)
614-614: LGTM!The ternary expression properly handles the redirect URL logic: augmenting an existing URL with UTM parameters when present, or generating the default upgrade link when absent.
classes/factories/FrmFieldFactory.php (1)
75-79: LGTM!The ternary refactor correctly preserves the original behavior: instantiate
FrmFieldDefaultwhen$classis empty, otherwise instantiate the resolved class. Both branches pass identical constructor arguments.classes/models/FrmReviews.php (1)
110-110: LGTM!The ternary correctly consolidates the rounding logic: entries ≤100 are rounded down to the nearest 10, otherwise to the nearest 50. Behavior is unchanged.
classes/helpers/FrmEmailSummaryHelper.php (1)
404-407: LGTM!The ternary correctly handles the border construction: when
$border_posis truthy, it generates the border CSS; otherwise, an empty string is used. This preserves the original behavior.classes/models/FrmEntry.php (3)
607-607: LGTM!The ternary correctly selects the appropriate
$whereclause based on whether$idis numeric. Behavior unchanged.
958-960: LGTM!The null coalescing operator correctly falls back to
get_created_at()whenupdated_atis not set or is null. This preserves the original behavior.
1015-1021: LGTM!The ternary correctly returns
falseon insert failure and$wpdb->insert_idon success. Behavior unchanged.classes/views/frm-entries/_sidebar-shared-pub.php (1)
16-18: LGTM!The ternary correctly handles the date format: when a custom format exists, it replaces full month names with abbreviated ones; otherwise, it falls back to the localized default. Behavior unchanged.
classes/helpers/FrmFormsListHelper.php (1)
203-210: Ternary for$classinget_viewsis behaviorally identicalThe new
$class = $status == $form_type ? ' class="current"' : '';matches the old if/else and keeps the generated markup unchanged.classes/helpers/FrmEntriesHelper.php (1)
203-207: Entry shortcode and browser-version ternaries look correct
- In
replace_default_message,$this_atts = ! empty( $add_atts ) ? array_merge( $atts, $add_atts ) : $atts;is equivalent to the prior if/else and keeps attribute precedence intact.- In
get_browser, the ternary assigning$versionbased on thestrriposcomparison preserves the previous logic for selecting the correct match index.No functional change introduced here.
Also applies to: 685-693
classes/models/FrmStyle.php (1)
262-275: Style sanitization and default-style ID handling are preserved
- The ternary in
sanitize_post_content(isset( $settings[$key] ) ? sanitize_textarea_field(...) : $defaults[$key]) maintains the same behavior as the old branch logic.- In
get_one,$this->id = $style ? $style->ID : 0;is equivalent to the previous explicit if/else when resolving the default style.Looks good.
Also applies to: 485-490
classes/helpers/FrmFieldsHelper.php (1)
495-505: Message/condition ternaries preserve original behavior
maybe_replace_substrings_with_field_name: when$field_nameis falsy, the ternary correctly picks “This value” only forunique_msgand “This field” otherwise, matching the previous nested ifs.value_meets_condition: the ternarystriposcheck forLIKEvsnot LIKEkeeps the same semantics (not LIKE→ substring absent,LIKE→ present).No behavior changes here.
Also applies to: 881-907
classes/models/fields/FrmFieldType.php (2)
261-263: Small ternary refactors in label/default/fill helpers are safe
for_label_html()now returns theforattribute or empty string via ternary; same as before.default_value_to_string()now collapses an all-empty array to''and otherwiseimplodes it, as previously.fill_values()now usesempty( $value ) ? $defaults : array_merge( $defaults, (array) $value );, preserving the original merge semantics.All look good.
Also applies to: 818-826, 1927-1929
1555-1596:add_aria_descriptionternary initialization keeps ARIA behavior unchangedInitializing
$describedbywith a ternary based on$aria_describedby_existsis equivalent to the old explicit if/else: you still get a split array of existing IDs when present, or an empty array otherwise. The subsequent error/description ordering logic is unaffected.No issues here.
classes/models/FrmField.php (4)
412-417: Array serialization increatestill matches original rulesThe new ternary inside the loop (
$k === 'default_value' ? FrmAppHelper::maybe_json_encode( $v ) : serialize( $v );) keeps the previous behavior of JSON-encoding onlydefault_valueand serializing all other array-valued columns.Looks correct.
860-871:get_typerefactor maintains cache and DB fallback semanticsBuilding
$wherewith a ternary and then callingFrmDb::get_var( 'frm_fields', $where, $col );mirrors the old numeric-id vs field-key branching.$typeis still always set in either the cache-hit or DB-fallback path before returning.
1473-1475:get_optiondispatcher ternary is equivalent
return is_array( $field ) ? self::get_option_in_array( ...) : self::get_option_in_object( ... );simply inlines the previous if/else without changing how array vs object fields are handled.
1512-1516:is_repeating_fieldternary retains original logic
$is_repeating_field = is_array( $field ) ? 'divider' === $field['type'] : 'divider' === $field->type;is a straight refactor of the prior branch. The final&& self::is_option_true( $field, 'repeat' )gate is unchanged, so repeating detection semantics remain the same.classes/models/FrmForm.php (1)
368-368: LGTM! Clean refactoring to ternary expressions.All four changes in this file successfully replace multi-line conditionals with clear, concise ternary expressions and null-coalescing operators:
- Line 368: Null-coalescing operator for field lookup is idiomatic
- Line 480: Ternary for sanitization logic is readable
- Line 877: Ternary for where clause construction is appropriate
- Line 1181: Ternary for form retrieval is clear
The refactorings preserve functional equivalence while improving code brevity.
Also applies to: 480-480, 877-877, 1181-1181
classes/helpers/FrmEntriesListHelper.php (1)
379-389: LGTM! Streamlined cell rendering logic.The refactoring consolidates the column value assignment into a single ternary expression (line 379) and simplifies the subsequent rendering logic. The behavior is functionally equivalent—hidden columns render empty strings, while visible columns render their values with appropriate action links when applicable.
classes/models/FrmAddon.php (1)
735-735: LGTM! Clear ternary refactorings.Both changes appropriately simplify conditional logic:
- Line 735: Ternary for multisite-aware option retrieval is idiomatic
- Lines 1029-1031: Message assignment consolidation maintains the original error-handling logic
The refactorings improve readability without altering behavior.
Also applies to: 1029-1031
classes/helpers/FrmXMLHelper.php (1)
225-225: LGTM! Effective ternary simplifications.All three ternary refactorings are appropriate:
- Line 225: Parent term ID fallback to 0 is clear
- Line 1704: Custom style fallback to 1 is appropriate
- Line 2256: Email parsing with fallback to empty array is correct
Each change reduces verbosity while maintaining the original logic.
Also applies to: 1704-1704, 2256-2256
classes/helpers/FrmFormsHelper.php (3)
85-86: Minor formatting adjustment.PHP closing/opening tag consolidation with no functional impact.
Also applies to: 235-236
258-258: LGTM! Clear ternary expressions.All three helper methods appropriately use ternaries for simple conditional returns:
- Line 258: Field name extraction is clear
- Line 269: Icon fallback logic is appropriate
- Line 1315: Form ID extraction is straightforward
Each refactoring improves conciseness without sacrificing clarity.
Also applies to: 269-269, 1315-1315
1394-1398: LGTM! Consolidated trash/delete logic.The ternary on line 1395 appropriately consolidates the EMPTY_TRASH_DAYS check. The overall if/elseif/else structure is clear:
- Trash status → restore option
- Delete permission → trash or delete based on EMPTY_TRASH_DAYS constant
- No permission → empty array
Behavior is preserved while improving code brevity.
classes/helpers/FrmAppHelper.php (5)
133-133: LGTM: Clean ternary conversion.The ternary operator appropriately handles both array and string inputs for the
$argsparameter.
177-177: LGTM: Appropriate null coalescing usage.The
??operator provides a clean fallback whenutm_mediumis not set in$query_args.
1626-1626: LGTM: Clean conditional link handling.The ternary appropriately adds UTM parameters to an existing link or generates a new upgrade link.
2660-2665: LGTM: Appropriate user lookup logic.The ternary cleanly differentiates between email and login lookups, with proper null checking and memory cleanup.
3649-3649: LGTM: Clear serialization handling.The ternary appropriately distinguishes between serialized and JSON-encoded data with proper fallback logic.
Add new rector rule for SimplifyIfElseToTernaryRector
No description provided.