Skip to content

PrefixAllGlobals: false negatives when checking group constant declarations #2560

@rodrigoprimo

Description

@rodrigoprimo

Bug Description

The sniff WordPress.NamingConventions.PrefixAllGlobals does not take into consideration that multiple constants can be declared using a single const keyword. When there is more than one constant declaration, the sniff will check only the name of the first constant, potentially leading to false negatives.

Minimal Code Snippet

The issue happens when running this command:

vendor/bin/phpcs -s --standard=WordPress --sniffs=WordPress.NamingConventions.PrefixAllGlobals test.php

... over a file containing this code:

<?php

// phpcs:set WordPress.NamingConventions.PrefixAllGlobals prefixes[] my_plugin

const MY_PLUGIN_CONSTANT = 'value', ANOTHER_CONSTANT = 'another_value';

I would expect to see a WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound error for the ANOTHER_CONSTANT constant, but no error is reported.

Error Code

WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound

Environment

Question Answer
PHP version 8.3.22
PHP_CodeSniffer version 3.13.2
WordPressCS version develop
PHPCSUtils version 1.1.0
PHPCSExtra version 1.4.0
WordPressCS install type git clone
IDE (if relevant) N/A

Additional Context (optional)

I believe the problem is related to the code below when the sniff gets the name of the constant without considering that there might be more than one constant declaration after T_CONST:

$constant_name_ptr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true );
if ( false === $constant_name_ptr ) {
// Live coding.
return;
}
$item_name = $this->tokens[ $constant_name_ptr ]['content'];
if ( \defined( '\\' . $item_name ) ) {
// Backfill for PHP native constant.
return;
}
if ( isset( $this->allowed_core_constants[ $item_name ] ) ) {
// Defining a WP Core constant intended for overruling.
return;
}
$error_text = 'Global constants defined';
$error_code = 'NonPrefixedConstantFound';
break;

Tested Against develop Branch?

  • I have verified the issue still exists in the develop branch of WordPressCS.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions