Repository navigation
Tokenizer: fatal error when a const name is the last non-empty token in a file #1451
Description
Describe the bug
PHPCS aborts with a fatal "Undefined array key" error while tokenizing a file when the name of a const declaration is the last non-empty token in the file (const NAME with nothing following it).
Code sample
<?php
const ATo reproduce
Steps to reproduce the behavior:
- Create a file called
test.phpwith the code sample above. - Run
phpcs test.php(the standard is irrelevant). - See the error message displayed:
FILE: test.php
--------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
--------------------------------------------------------------------------------
1 | ERROR | An error occurred during processing; checking has been aborted.
| | The error message was: Undefined array key 6 in
| | src/Tokenizers/PHP.php on line 2583
--------------------------------------------------------------------------------
Expected behavior
I would expect PHPCS to tokenize the file without a fatal error, so that the rest of the file can still be checked.
Versions
| Operating System | Ubuntu |
| PHP version | PHP 8.5 |
| PHP_CodeSniffer version | 4.x |
| Standard | N/A |
| Install type | git clone |
Additional context
When $insideConstDeclaration is true, a loop walks forward from the constant name to the next non-empty token and then checks whether that token is an =:
PHP_CodeSniffer/src/Tokenizers/PHP.php
Lines 2573 to 2586 in 33581e9
| for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { | |
| if (is_array($tokens[$i]) === true | |
| && isset(Tokens::EMPTY_TOKENS[$tokens[$i][0]]) === true | |
| ) { | |
| continue; | |
| } | |
| break; | |
| } | |
| if ($tokens[$i] === '=') { | |
| $preserveTstring = true; | |
| $insideConstDeclaration = false; | |
| } |
When the constant name is the last non-empty token in the file, the for loop ends via its $i < $numTokens condition with $i equal to $numTokens. The following $tokens[$i] === '=' check then reads an index that does not exist, which triggers the "Undefined array key" error.
The constant-handling code involved was added in #321 (support for typed OO constants).
Please confirm
- I have searched the issue list and am not opening a duplicate issue.
- I have read the Contribution Guidelines and this is not a support question.
- I confirm that this bug is a bug in PHP_CodeSniffer and not in one of the external standards.
- I have verified the issue still exists in the
4.xbranch of PHP_CodeSniffer.
Activity