Skip to content

Tokenizer: fatal error when a const name is the last non-empty token in a file #1451

Closed

Description

@rodrigoprimo

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 A

To reproduce

Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above.
  2. Run phpcs test.php (the standard is irrelevant).
  3. 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 =:

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.x branch of PHP_CodeSniffer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions