Skip to content

Commit

Permalink
PHP 8.3 | Generic/LowerCaseConstant: add support for typed constants
Browse files Browse the repository at this point in the history
Type declarations are explicitly not checked by this sniff.

PHP 8.3 introduces typed constants. This means that the sniff now also needs to ensure that it doesn't flag non-lowercase `true`/`false`/`null` in the type declaration for a constant.

Fixed now. Includes tests.
  • Loading branch information
jrfnl committed Feb 8, 2024
1 parent de3b745 commit b65551d
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Standards/Generic/Sniffs/PHP/LowerCaseConstantSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ public function register()
$targets[] = T_CLOSURE;
$targets[] = T_FN;

// Register constant keyword to filter out type declarations.
$targets[] = T_CONST;

return $targets;

}//end register()
Expand All @@ -101,6 +104,19 @@ public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();

// Skip over potential type declarations for constants.
if ($tokens[$stackPtr]['code'] === T_CONST) {
// Constant must always have a value assigned to it, so we can just look for the assignment
// operator. Anything between the const keyword and the assignment can be safely ignored.
$skipTo = $phpcsFile->findNext(T_EQUAL, ($stackPtr + 1));
if ($skipTo !== false) {
return $skipTo;
}

// If we're at the end of the file, just return.
return;
}

/*
* Skip over type declarations for properties.
*
Expand Down
8 changes: 8 additions & 0 deletions src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,14 @@ readonly class Properties {
}
}

// PHP 8.3 introduces typed constants.
class TypedConstants {
const MyClass|NULL|TRUE|FALSE MYCONST = FALSE;
}

// Global constants can not be typed.
const MYCONST = TRUE;

// Last coding/parse error.
// This has to be the last test in the file.
function UnclosedCurly (): FALSE {
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,14 @@ readonly class Properties {
}
}

// PHP 8.3 introduces typed constants.
class TypedConstants {
const MyClass|NULL|TRUE|FALSE MYCONST = false;
}

// Global constants can not be typed.
const MYCONST = true;

// Last coding/parse error.
// This has to be the last test in the file.
function UnclosedCurly (): FALSE {
2 changes: 2 additions & 0 deletions src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ public function getErrorList($testFile='')
121 => 1,
125 => 1,
129 => 1,
149 => 1,
153 => 1,
];

case 'LowerCaseConstantUnitTest.js':
Expand Down

0 comments on commit b65551d

Please sign in to comment.