Skip to content

False Positive: Class Constants Flagged as Unescaped Output #1

@RyanBayne

Description

@RyanBayne

Issue Description

The WordPress Coding Standards checker incorrectly flags class constants as unescaped output when they are already properly handled.

Example Code:

var useAjax = <?php echo esc_js( self::USE_URL_NAVIGATION ? 'false' : 'true' ); ?>;

WordPress.Security.EscapeOutput.OutputNotEscaped
All output should be run through an escaping function, found 'self'.

The Problem
The PHPCS parser incorrectly identifies self as a variable that needs escaping, when it's actually:

1. A PHP keyword (class reference)
3. Accessing a constant (USE_URL_NAVIGATION)
5. Already wrapped in esc_js()
7. Outputting hardcoded boolean literals ('false' or 'true')

The error message "found 'self'" is misleading because:

- It suggests self is unescaped output
- It doesn't recognize that self::CONSTANT is not user input
- It doesn't see that the entire expression is inside esc_js()
- It treats class constants the same as variables

Current Workarounds
Developers must use one of these approaches:

Add PHPCS ignore comment:

// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Class constant, not user input
var useAjax = <?php echo self::USE_URL_NAVIGATION ? 'false' : 'true'; ?>;

OR Remove unnecessary escaping (since output is hardcoded literals):

var useAjax = <?php echo self::USE_URL_NAVIGATION ? 'false' : 'true'; ?>;

Proposed Improvements
The WordPress Coding Standards could be improved to:

Better Context Detection

Recognize self::, static::, and ClassName:: as safe class references

Differentiate between class constants and variables

Understand that constants defined with const are not user input

More Specific Error Messages

Current: "found 'self'"

Improved: "found class reference 'self::USE_URL_NAVIGATION' - if this is a constant, add phpcs:ignore comment with explanation"

Suggest Solutions in Error Message

Include the ignore comment syntax

Explain why the code might be flagged

Provide context-specific guidance

Differentiate Between Input Types

User input variables: $_GET, $_POST, $_REQUEST → Must escape

Class constants: self::CONSTANT, ClassName::CONSTANT → Safe

Hardcoded values: 'string', 123, true → Safe

Function returns: Depends on function → Context-aware checking

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions