Skip to content

Commit

Permalink
PHP 8.3 | Generic/UpperCaseConstantName: add support for typed constants
Browse files Browse the repository at this point in the history
This sniff is specifically targeted at constant names.

PHP 8.3 introduces typed constants. This means that the sniff now needs to jump over a potentially declared constant type to get at the constant name.

Fixed now.

Includes tests.

Fixes squizlabs/PHP_CodeSniffer 3927
Closes squizlabs/PHP_CodeSniffer 3936
  • Loading branch information
jrfnl committed Feb 15, 2024
1 parent 7240235 commit 45bf3ad
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,16 @@ public function process(File $phpcsFile, $stackPtr)
$tokens = $phpcsFile->getTokens();

if ($tokens[$stackPtr]['code'] === T_CONST) {
// This is a class constant.
$constant = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
// This is a constant declared with the "const" keyword.
// This may be an OO constant, in which case it could be typed, so we need to
// jump over a potential type to get to the name.
$assignmentOperator = $phpcsFile->findNext([T_EQUAL, T_SEMICOLON], ($stackPtr + 1));
if ($assignmentOperator === false || $tokens[$assignmentOperator]['code'] !== T_EQUAL) {
// Parse error/live coding. Nothing to do. Rest of loop is moot.
return;
}

$constant = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($assignmentOperator - 1), ($stackPtr + 1), true);
if ($constant === false) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,13 @@ class ClassConstBowOutTest {
}

$foo->getBar()?->define('foo');

// PHP 8.3 introduces typed constants.
class TypedConstants {
const MISSING_VALUE; // Parse error.
const MyClass MYCONST = new MyClass;
const int VALID_NAME = 0;
const INT invalid_name = 0;
const FALSE false = false; // Yes, false can be used as a constant name, don't ask.
const array ARRAY = array(); // Same goes for array.
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public function getErrorList()
19 => 1,
28 => 1,
30 => 1,
40 => 1,
41 => 1,
];

}//end getErrorList()
Expand Down

0 comments on commit 45bf3ad

Please sign in to comment.