Skip to content

Update redundant empty sniff to also catch conditions with && and ||#2758

Merged
Crabcyborg merged 2 commits into
masterfrom
update_redundant_empty_sniff_to_catch_more_cases
Jan 9, 2026
Merged

Update redundant empty sniff to also catch conditions with && and ||#2758
Crabcyborg merged 2 commits into
masterfrom
update_redundant_empty_sniff_to_catch_more_cases

Conversation

@Crabcyborg
Copy link
Copy Markdown
Contributor

No description provided.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 9, 2026

Walkthrough

This PR systematically refactors conditional logic across the codebase by replacing PHP's empty() function calls with direct truthiness/falsy checks. Additionally, it expands a PHPCS sniff to better detect redundant empty() calls in conditional contexts beyond just if-statements, including boolean expressions.

Changes

Cohort / File(s) Summary
Controller conditional refactoring
classes/controllers/FrmAddonsController.php, classes/controllers/FrmDashboardController.php, classes/controllers/FrmEntriesController.php
Simplified guard conditions by replacing empty() / !empty() checks with direct truthiness/falsy tests. Affects activation URL validation, banner-closed tracking, and form ID guards.
Helper utility refactoring
classes/helpers/FrmAppHelper.php, classes/helpers/FrmXMLHelper.php
Converted empty() checks to truthiness checks in date/time formatting and autoresponder field selection logic. Potential behavioral change: numeric 0 now passes checks previously blocked by empty().
Model conditional simplification
classes/models/FrmPluginSearch.php, classes/models/FrmSettings.php, classes/models/FrmUsage.php, classes/models/fields/FrmFieldUrl.php
Replaced empty() conditions with truthiness checks in hint dismissal, menu configuration, UUID regeneration, and URL field validation. Note: String '0' now treated as non-empty.
PHPCS sniff logic expansion
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php
Refactored sniff detection to handle both if-conditions and boolean expressions (&&, ||) rather than only if-contexts. Introduced new private helpers (getStatementContext, isInBooleanExpression, findStatementStart) and updated context-tracking logic from if-token to statement-token level.
Test assertion refactoring
tests/phpunit/misc/test_FrmCSVExportHelper.php
Simplified CSV path assertion from !empty() check to direct truthiness test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to assess whether the description relates to the changeset. Add a description explaining the motivation, implementation details, or testing for the changes made to the sniff and affected files.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: updating a PHP CodeSniffer sniff to detect redundant empty() calls in more contexts (boolean expressions with && and ||).
Docstring Coverage ✅ Passed Docstring coverage is 94.44% 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

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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
classes/helpers/FrmXMLHelper.php (1)

2363-2400: Harden $email_field parsing: avoid str_contains()/array edge cases.

$email_field can become an int (default 0) or an array (after explode()), which risks a PHP 8+ TypeError (str_contains) or storing an unexpected type into email_to. Since this block is being refactored, it’s a good spot to normalize $email_field to a string.

Proposed fix
-			$email_field = $form_options['ar_email_to'] ?? 0;
+			$email_field = (string) ( $form_options['ar_email_to'] ?? '' );

-			if ( str_contains( $email_field, '|' ) ) {
+			if ( $email_field && str_contains( $email_field, '|' ) ) {
 				// data from entries field
 				$email_field = explode( '|', $email_field );

 				if ( isset( $email_field[1] ) ) {
 					$email_field = $email_field[1];
+				} else {
+					$email_field = '';
 				}
 			}

-			if ( is_numeric( $email_field ) && $email_field ) {
+			if ( is_numeric( $email_field ) && $email_field ) {
 				$email_field = '[' . $email_field . ']';
 			}
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php (1)

403-420: Remove unused findContainingIf method.

This method is not called anywhere in the codebase after the refactoring introduced getStatementContext and isInIfCondition. It can be safely removed.

🧹 Nitpick comments (5)
classes/models/FrmSettings.php (1)

353-353: Simplify the redundant condition.

The condition $mu_menu && $mu_menu checks the same value twice. This should be simplified to just $mu_menu.

♻️ Proposed simplification
-		if ( $mu_menu && $mu_menu ) {
+		if ( $mu_menu ) {
classes/controllers/FrmDashboardController.php (1)

362-366: Consider guarding in_array with is_array(...) for robustness.

If the stored option is ever corrupted/non-array, in_array(..., $banner_closed_by_users, true) can throw in PHP 8+. Not introduced by this change, but easy to harden while touching this line.

Proposed hardening
-		return $banner_closed_by_users && in_array( $user_id, $banner_closed_by_users, true );
+		return is_array( $banner_closed_by_users ) && $banner_closed_by_users && in_array( $user_id, $banner_closed_by_users, true );
classes/controllers/FrmAddonsController.php (1)

1335-1349: Type-harden hash_equals inputs to avoid PHP 8+ TypeError on unexpected option values.

If frm_connect_token is ever stored as a non-string (corrupted option), hash_equals can fatally error. Easy to guard while touching this line.

Proposed hardening
 		// Verify auth.
 		$auth = get_option( 'frm_connect_token' );
-		return $auth && hash_equals( $auth, $post_auth );
+		return is_string( $auth ) && '' !== $auth && hash_equals( $auth, $post_auth );
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php (2)

189-189: Remove unused variable $tokens.

This variable is declared but never used within the method, as the work is delegated to helper methods that fetch tokens themselves.

🧹 Suggested fix
 private function getStatementContext( File $phpcsFile, $stackPtr ) {
-    $tokens = $phpcsFile->getTokens();
-
     // Check if in an if/elseif condition.
     $ifContext = $this->isInIfCondition( $phpcsFile, $stackPtr );

237-240: Redundant condition check.

At this point in the loop, $code cannot be T_OPEN_PARENTHESIS since that case returns on line 230 or 234. The condition is always true when reached.

🧹 Suggested fix
-            // If we hit something else, stop.
-            if ( $code !== T_OPEN_PARENTHESIS ) {
-                return false;
-            }
+            // If we hit something else (not whitespace, !, or open paren), stop.
+            return false;
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 46d9ff4 and 62cdc03.

📒 Files selected for processing (11)
  • classes/controllers/FrmAddonsController.php
  • classes/controllers/FrmDashboardController.php
  • classes/controllers/FrmEntriesController.php
  • classes/helpers/FrmAppHelper.php
  • classes/helpers/FrmXMLHelper.php
  • classes/models/FrmPluginSearch.php
  • classes/models/FrmSettings.php
  • classes/models/FrmUsage.php
  • classes/models/fields/FrmFieldUrl.php
  • phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php
  • tests/phpunit/misc/test_FrmCSVExportHelper.php
🧰 Additional context used
🧬 Code graph analysis (2)
classes/controllers/FrmEntriesController.php (1)
classes/helpers/FrmAppHelper.php (2)
  • FrmAppHelper (6-5061)
  • is_admin (587-596)
classes/controllers/FrmAddonsController.php (2)
classes/models/FrmInstallPlugin.php (2)
  • activate_url (66-68)
  • is_installed (45-47)
classes/models/FrmPluginSearch.php (1)
  • is_installed (361-364)
🪛 PHPMD (2.15.0)
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php

189-189: Avoid unused local variables such as '$tokens'. (undefined)

(UnusedLocalVariable)

⏰ 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: Cypress
  • GitHub Check: PHP 7.4 tests in WP 6.9
  • GitHub Check: PHP 8 tests in WP 6.9
🔇 Additional comments (12)
classes/controllers/FrmEntriesController.php (1)

753-753: LGTM! Guard clause refactored correctly.

The change from empty($form_id) to ! $form_id maintains equivalent behavior since $form_id is cast to an absolute integer via absint. Both expressions return true for 0 and false for positive integers.

tests/phpunit/misc/test_FrmCSVExportHelper.php (1)

168-168: LGTM! Test assertion simplified correctly.

The truthiness check $csv_path is equivalent to ! empty($csv_path) for string validation. The compound assertion with is_string() and file_exists() provides adequate validation.

classes/models/FrmUsage.php (1)

57-57: LGTM! UUID regeneration condition simplified correctly.

The change from empty( $uuid ) to ! $uuid is semantically equivalent for this use case. Both return true when get_option() returns false (option not set) or an empty string, triggering UUID regeneration as intended.

classes/models/FrmPluginSearch.php (1)

226-226: LGTM! Dismissed hints check simplified correctly.

The change from ! empty( $dismissed_hints ) to $dismissed_hints maintains equivalent behavior. Both expressions correctly handle the case where get_option() returns false (option not set) or an empty array, returning an empty array as the fallback.

classes/helpers/FrmXMLHelper.php (1)

2390-2400: Truthiness update for from generation looks OK.

classes/helpers/FrmAppHelper.php (2)

3209-3219: add_time_to_date: truthiness check is fine and keeps whitespace-only formats from rendering.


3575-3584: select_current_page: simplified condition reads well; behavior should be equivalent.

classes/models/fields/FrmFieldUrl.php (1)

68-87: FrmFieldUrl::validate: change looks OK, but please confirm '0' should still be treated as blank.

Using ! $value keeps PHP’s special-casing where '0' is falsy; that matches prior empty() behavior, but it’s worth confirming this is the desired input semantics for URL fields.

classes/controllers/FrmAddonsController.php (1)

833-842: prepare_addons: truthy $activate_url check is fine.

phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/RedundantEmptyOnAssignedVariableSniff.php (3)

254-287: LGTM!

The boolean expression detection logic correctly handles both positions (before and after empty()) and accounts for the negation operator.


297-320: LGTM!

Clean implementation for finding statement boundaries with appropriate stopping conditions at function/class scopes.


359-393: LGTM!

The refactored method correctly uses the statement token for scope level comparison, enabling the sniff to work with the broader set of boolean expression contexts.

@Crabcyborg Crabcyborg merged commit b778b1a into master Jan 9, 2026
15 of 16 checks passed
@Crabcyborg Crabcyborg deleted the update_redundant_empty_sniff_to_catch_more_cases branch January 9, 2026 16:28
stephywells pushed a commit that referenced this pull request Apr 4, 2026
…_to_catch_more_cases

Update redundant empty sniff to also catch conditions with && and ||
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