Skip to content

New sniff to encourage using the best fit wp esc function#2816

Merged
Crabcyborg merged 1 commit into
masterfrom
new_sniff_to_encourage_using_the_right_wp_esc_function
Jan 16, 2026
Merged

New sniff to encourage using the best fit wp esc function#2816
Crabcyborg merged 1 commit into
masterfrom
new_sniff_to_encourage_using_the_right_wp_esc_function

Conversation

@Crabcyborg

@Crabcyborg Crabcyborg commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

This sniff encourages changing echo esc_html( __( ... type of code to use esc_html_e instead for example.

Summary by CodeRabbit

  • Code Quality
    • Added a new PHP code analysis rule to the development toolkit to identify and flag instances where function calls can be modernized, promoting consistent use of combined translation and escape functions throughout the codebase.
    • Refactored existing code to comply with the updated coding standards.

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

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a new PHP_CodeSniffer sniff that detects when developers combine echo with HTML escaping and translation functions, recommending a more concise alternative. An existing file is updated to follow this pattern, and the new sniff is registered in the codebase's ruleset.

Changes

Cohort / File(s) Summary
Import Form Update
classes/views/xml/import_form.php
Simplified export heading output from echo esc_html( __( 'Export ...', 'formidable' ) ) to esc_html_e( 'Export ...', 'formidable' ), reducing redundant function wrapping
New Code Sniffer Implementation
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php
Implements PHP_CodeSniffer sniff to detect echo <escape>( <translate>() ) patterns and suggest replacement with combined functions like esc_html_e() or esc_attr_e(). Maintains replacement mappings, validates token structure, and provides fixable errors
Ruleset Configuration
phpcs-sniffs/Formidable/ruleset.xml
Registered new Formidable.CodeAnalysis.PreferEscHtmlE rule within the Code Analysis section

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 With ears perked high and code so clean,
I've hopped past echoes—quite the scene!
Now esc_html_e() takes the stage,
A sniff to guide each developer's page,
Combined translations, shorter and keen! 🎉

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a new PHP_CodeSniffer sniff that encourages using the most appropriate WordPress escaping function instead of redundant patterns.
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

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.

@Crabcyborg
Crabcyborg merged commit 542dc94 into master Jan 16, 2026
35 of 36 checks passed
@Crabcyborg
Crabcyborg deleted the new_sniff_to_encourage_using_the_right_wp_esc_function branch January 16, 2026 12:58

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php`:
- Around line 120-134: The sniff currently assumes nothing meaningful exists
between $translateCloseParen and $escapeCloseParen and can incorrectly match
expressions with concatenation (e.g. ". ' extra'"); update the validation to
iterate tokens between $translateCloseParen + 1 and $escapeCloseParen - 1 and
bail out (return) if any token other than T_WHITESPACE (or T_COMMENT if you
prefer to allow comments) is found. Locate this check near the existing
$translateCloseParen and $escapeCloseParen logic in PreferEscHtmlESniff.php and
perform the token-scan before computing $semicolon so the fixer will not
auto-fix when extra non-whitespace content is present.
📜 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 21b5893 and a6f9e2f.

📒 Files selected for processing (3)
  • classes/views/xml/import_form.php
  • phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php
  • phpcs-sniffs/Formidable/ruleset.xml
🧰 Additional context used
📓 Path-based instructions (1)
**/*.php

⚙️ CodeRabbit configuration file

**/*.php: - Do not make suggestions when we use x.x for a version placeholder. This is used like "@SInCE x.x" in a PHP doc comment, but also like 'x.x' when functions like _deprecated_function() are used.

  • Treat these placeholders as acceptable in this codebase.

Files:

  • phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php
  • classes/views/xml/import_form.php
🧬 Code graph analysis (1)
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php (1)
phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/FlipNegativeTernarySniff.php (1)
  • getTokensAsString (297-306)
⏰ 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: Cypress
  • GitHub Check: PHP 7.4 tests in WP 6.9
  • GitHub Check: PHP 8 tests in WP 6.9
  • GitHub Check: Cypress
  • GitHub Check: PHP 7.4 tests in WP 6.9
  • GitHub Check: PHP 8 tests in WP 6.9
🔇 Additional comments (4)
classes/views/xml/import_form.php (1)

72-72: LGTM!

The change correctly converts echo esc_html( __( ... ) ) to the combined esc_html_e( ... ) function, aligning with the new sniff's enforcement. This is consistent with the existing patterns elsewhere in this file.

phpcs-sniffs/Formidable/ruleset.xml (1)

34-34: LGTM!

The new sniff rule reference is correctly added in the Code Analysis section and follows the existing naming convention.

phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php (2)

29-47: LGTM!

The replacements mapping is well-structured, covering all valid combinations of escape and translation functions. The register function correctly listens for T_ECHO tokens.


136-158: LGTM!

The argument extraction using getTokensAsString() with correct start position and length is properly implemented. The fix logic correctly removes the original tokens and inserts the combined function call with trimmed arguments.

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

Comment on lines +120 to +134
$translateCloseParen = $tokens[ $translateOpenParen ]['parenthesis_closer'];

// Find the closing parenthesis of the escape function.
if ( ! isset( $tokens[ $openParen ]['parenthesis_closer'] ) ) {
return;
}

$escapeCloseParen = $tokens[ $openParen ]['parenthesis_closer'];

// Find the semicolon.
$semicolon = $phpcsFile->findNext( T_WHITESPACE, $escapeCloseParen + 1, null, true );

if ( false === $semicolon || $tokens[ $semicolon ]['code'] !== T_SEMICOLON ) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing validation may cause incorrect auto-fixes.

The sniff doesn't verify that there's nothing between $translateCloseParen and $escapeCloseParen except whitespace. For code like:

echo esc_html( __( 'text', 'domain' ) . ' extra' );

The sniff would incorrectly match and produce esc_html_e( 'text', 'domain' );, silently losing . ' extra'.

🐛 Proposed fix: Add validation after line 127
 		$escapeCloseParen = $tokens[ $openParen ]['parenthesis_closer'];
 
+		// Ensure nothing exists between translation close paren and escape close paren except whitespace.
+		$tokenBetween = $phpcsFile->findNext( T_WHITESPACE, $translateCloseParen + 1, $escapeCloseParen, true );
+
+		if ( false !== $tokenBetween ) {
+			return;
+		}
+
 		// Find the semicolon.
 		$semicolon = $phpcsFile->findNext( T_WHITESPACE, $escapeCloseParen + 1, null, true );
🤖 Prompt for AI Agents
In `@phpcs-sniffs/Formidable/Sniffs/CodeAnalysis/PreferEscHtmlESniff.php` around
lines 120 - 134, The sniff currently assumes nothing meaningful exists between
$translateCloseParen and $escapeCloseParen and can incorrectly match expressions
with concatenation (e.g. ". ' extra'"); update the validation to iterate tokens
between $translateCloseParen + 1 and $escapeCloseParen - 1 and bail out (return)
if any token other than T_WHITESPACE (or T_COMMENT if you prefer to allow
comments) is found. Locate this check near the existing $translateCloseParen and
$escapeCloseParen logic in PreferEscHtmlESniff.php and perform the token-scan
before computing $semicolon so the fixer will not auto-fix when extra
non-whitespace content is present.

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