Skip to content

Fatal error if you try to get the declaration name of an arrow function #3766

@antonioeatgoat

Description

@antonioeatgoat

Describe the bug
If you try to get the declaration name of an arrow function using the method File::getDeclarationName(), it will throws an exception.

It looks like it is legit to use the method for a closure, since there is this condition here, so probably the same condition should be added also for T_FN.

Custom code sniff sample

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

class MyCustomCodeSniff implements Sniff
{
    public function register()
    {
        return [T_FUNCTION, T_CLOSURE, T_FN];
    }

    public function process(File $file, $position)
    {
        /** @var array<int, array<string, mixed>> $tokens */
        $tokens = $file->getTokens();

        if (!in_array(($tokens[$position]['code'] ?? null), [T_FUNCTION, T_CLOSURE, T_FN], true)) {
            return;
        }

        $functionStart = (int)($tokens[$position]['scope_opener'] ?? 0);
        $functionEnd = (int)($tokens[$position]['scope_closer'] ?? 0);

        if (($functionStart < 0) || ($functionEnd <= 0)) {
            return;
        }

        $declarationName = $file->getDeclarationName($position);

        // ... do other thins here ...
    }
}

To reproduce
Steps to reproduce the behavior:

  1. Create a file called test.php which contain a simple fn() => 'x';
  2. Add the custom sniff rule
  3. Run phpcs test.php ...
  4. See error message displayed
An error occurred during processing; checking has been aborted. The error message was: Token type "T_FN" is not T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM (Internal.Exception)

Expected behavior
A condition for T_FN is added as explained above, so that the method File::getDeclarationName() can return null instead of throwing an exception, when used on an arrow function.

Versions (please complete the following information):

  • OS: MacOS 13.1
  • PHP: 7.4
  • PHPCS: 3.7.2
  • Standard:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions