Skip to content

New sniff to simplify ternaries that check the opposite thing in the …#2796

Merged
Crabcyborg merged 3 commits into
masterfrom
new_sniff_to_simplify_ternaries_that_check_the_same_thing_twice_but_opposite
Jan 14, 2026
Merged

New sniff to simplify ternaries that check the opposite thing in the …#2796
Crabcyborg merged 3 commits into
masterfrom
new_sniff_to_simplify_ternaries_that_check_the_same_thing_twice_but_opposite

Conversation

@Crabcyborg
Copy link
Copy Markdown
Contributor

@Crabcyborg Crabcyborg commented Jan 14, 2026

…2nd condition group

The sniff detects (A && B) || (!A && C) patterns and converts them to A ? B : C ternary expressions.

Summary by CodeRabbit

  • Refactor

    • Simplified conditional logic in several helper and model areas to improve readability and consistency.
  • Chores

    • Added a new code-quality rule to detect and automatically suggest simplifying paired conditional expressions into ternary forms.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 14, 2026

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'path_instructions'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
📝 Walkthrough

Walkthrough

Adds a new PHP_CodeSniffer sniff that detects dual-group boolean conditions suitable for ternary replacement and applies concise ternary refactors in three helper/model files (conditional checks and description replacement logic).

Changes

Cohort / File(s) Summary
Helper ternary refactors
classes/helpers/FrmAppHelper.php, classes/helpers/FrmFieldsHelper.php, classes/models/FrmFieldFormHtml.php
Replaced compound boolean expressions with simpler ternary-based returns/assignments while preserving existing behavior (array vs scalar checks, and description-shortcode replacement condition).
New CodeSniffer sniff
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php
New sniff detecting patterns of two parenthesized groups joined by `
PHPCS ruleset update
phpcs.xml
Registers the new Formidable.CodeAnalysis.SimplifyDualConditionToTernary sniff in the ruleset.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐇 I hop through code in morning light,
Hunting || and && with delight,
Where opposites meet in parenthesis' lair,
I stitch one ternary with careful care,
Hooray — less branching, tidier air! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The PR title references 'ternaries that check the opposite thing' but the actual implementation creates a new sniff that simplifies dual-condition patterns (A && B) || (!A && C) to ternary form. The title is truncated ('…') and partially misleading about what the sniff does. Complete the title and clarify that it adds a sniff to detect and simplify dual-condition boolean patterns to ternaries, e.g., 'Add sniff to simplify dual-condition boolean expressions to ternaries'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

🧹 Recent nitpick comments
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php (2)

324-347: Consider tracking additional bracket types for robustness.

The depth tracking only accounts for parentheses. Edge cases with array syntax or closures inside conditions (e.g., (fn() => true && ...) || ...) could potentially cause incorrect && detection.

This is a minor edge case for typical usage patterns, but for completeness, consider also tracking T_OPEN_SQUARE_BRACKET/T_CLOSE_SQUARE_BRACKET and T_OPEN_CURLY_BRACKET/T_CLOSE_CURLY_BRACKET.


60-62: Note: strpos, stripos, and preg_match return int|false, not boolean.

These functions are commonly used in boolean contexts, so including them is reasonable for practical purposes. However, transforming expressions using these may slightly alter semantics since 0 (valid match at position 0) is falsy but distinct from false. This is likely acceptable for the intended use cases.


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c5167c5 and 81622d9.

📒 Files selected for processing (1)
  • phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php
⏰ 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). (3)
  • GitHub Check: PHP 7.4 tests in WP 6.9
  • GitHub Check: PHP 8 tests in WP 6.9
  • GitHub Check: Cypress
🔇 Additional comments (3)
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php (3)

357-365: LGTM!

The logic correctly verifies that exactly one condition is negated and that both conditions have identical content.


376-460: LGTM!

The boolean expression validation is thorough: it checks for comparison operators at the top level and verifies against the known boolean-returning functions list, including negated function calls.


471-480: LGTM!

Simple and correct token content extraction.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
classes/models/FrmFieldFormHtml.php (1)

213-220: Looks behavior-preserving; consider simpler boolean equivalence for readability.

$should_replace = $is_html ? $wp_processed : ! $wp_processed; is equivalent to $is_html === $wp_processed, which may be easier to scan in the future.

Proposed tweak
-		$is_html        = 'html' === $this->field_obj->get_field_column( 'type' );
-		$should_replace = $is_html ? $wp_processed : ! $wp_processed;
+		$is_html        = 'html' === $this->field_obj->get_field_column( 'type' );
+		$should_replace = ( $is_html === $wp_processed );
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php (2)

139-180: Consider skipping comments (not just whitespace) inside groups to improve match rate.

getFirstCondition / getRestOfCondition currently only skip T_WHITESPACE, so inline comments between tokens can prevent detection (false negatives). Using Tokens::$emptyTokens consistently would make this more resilient.

Also applies to: 193-237


281-289: Normalize condition text before comparison to reduce false negatives.

areOppositeConditions requires exact string equality for $cond['content']; small formatting differences (extra parens/whitespace) will miss otherwise-valid cases. Consider normalizing whitespace and optionally stripping redundant outer parens before comparing.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6470550 and c5167c5.

📒 Files selected for processing (5)
  • classes/helpers/FrmAppHelper.php
  • classes/helpers/FrmFieldsHelper.php
  • classes/models/FrmFieldFormHtml.php
  • phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php
  • phpcs.xml
🧰 Additional context used
🧬 Code graph analysis (1)
classes/helpers/FrmFieldsHelper.php (1)
classes/helpers/FrmAppHelper.php (1)
  • checked (2419-2423)
⏰ 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). (3)
  • GitHub Check: PHP 8 tests in WP 6.9
  • GitHub Check: PHP 7.4 tests in WP 6.9
  • GitHub Check: Cypress
🔇 Additional comments (3)
classes/helpers/FrmAppHelper.php (1)

2431-2438: LGTM: clearer control flow with the ternary.

This keeps the same behavior while being more compact.

classes/helpers/FrmFieldsHelper.php (1)

679-709: LGTM: simplified default-value check without changing behavior.

The ternary keeps the same “array vs scalar” semantics and reads cleaner inline.

phpcs.xml (1)

240-261: Sniff reference is valid. The SimplifyDualConditionToTernary sniff file exists at phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/SimplifyDualConditionToTernarySniff.php with the correct class definition, and PHPCS will resolve it without errors via the dealerdirect composer plugin's automatic installed_paths configuration.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@Crabcyborg Crabcyborg merged commit fdbb9f5 into master Jan 14, 2026
16 checks passed
@Crabcyborg Crabcyborg deleted the new_sniff_to_simplify_ternaries_that_check_the_same_thing_twice_but_opposite branch January 14, 2026 15:40
stephywells pushed a commit that referenced this pull request Apr 4, 2026
…ies_that_check_the_same_thing_twice_but_opposite

New sniff to simplify ternaries that check the opposite thing in the …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant