Skip to content

Constants::getNames(): new method to retrieve constant names from const declarations #727

@rodrigoprimo

Description

@rodrigoprimo

Is your feature request related to a problem?

When multiple constants are declared in a single const statement (e.g., const FOO = 10, BAR = 15;), there is currently no straightforward way to retrieve all the constant names from a T_CONST token.

Without a dedicated method, sniffs that need to check all constant names in a multi-constant declaration must manually walk through the tokens to identify each constant name, which requires additional logic.

Describe the solution you'd like

Add a new Constants::getNames() method that would:

  • Accept a $stackPtr pointing to a T_CONST token.
  • Work for both class constants and global constants (https://3v4l.org/r0Ldi demonstrates that multi-constant declaration syntax for both class and global constants is supported since PHP 5.3).
  • Return an array of all constant names with their corresponding stack pointers.

Example usage

Given the following code:

class Example {
    const FOO = 10, BAR = 15, BAZ = 20;
}

Calling Constants::getNames($phpcsFile, $stackPtr) where $stackPtr points to the T_CONST token would return:

[
    'FOO' => #,
    'BAR' => #,
    'BAZ' => #,
]

And given the following code:

const GLOBAL_A = 1, GLOBAL_B = 2;

Calling Constants::getNames($phpcsFile, $stackPtr) where $stackPtr points again to the T_CONST token would return:

[
    'GLOBAL_A' => #,
    'GLOBAL_B' => #,
]

Additional context

Loosely related to #690.

  • I intend to create a pull request to implement this feature.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions