sirbrillig / phpcs-variable-analysis

Find undefined and unused variables with the PHP Codesniffer static analysis tool.
Other
136 stars 14 forks source link

Ternary operator inside arrow function #297

Closed tomrajnoha closed 1 year ago

tomrajnoha commented 1 year ago

Consider the below MRE, which was OK for phpcs-variable-analysis v2.11.12, but receives a warning in v2.11.14 for the part of the code on the last line (between question mark and colon).

Warning: Variable $cls is undefined. (VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable)

Note that PHP (8.0) has no issue with the code and it works as expected. As far as I can tell, it might be connected to PR https://github.com/sirbrillig/phpcs-variable-analysis/pull/296.

class Test
{
    public function status(): bool
    {
        return true;
    }

    public static function hello(callable $callback): void
    {
        print('Hello');
    }
}

Test::hello(fn(Test $cls) => $cls->status() ? $cls : null);

This workaround can fix it for now.

class Test
{
    public function status(): bool
    {
        return true;
    }

    public static function hello(callable $callback): void
    {
        print('Hello');
    }
}

Test::hello(static function (Test $cls): ?Test {
    return $cls->status() ? $cls : null;
});
sirbrillig commented 1 year ago

Hm... yes, it looks like the scope detection for arrow functions is still buggy. Even before https://github.com/sirbrillig/phpcs-variable-analysis/pull/296, it would have broken for versions of PHP/phpcs that did not support arrow functions, so in a way this is good to discover.

tomrajnoha commented 1 year ago

Amazing, thank you very much for this quick fix. I will check later if I can be of some help dealing with these detections.

sirbrillig commented 1 year ago

This should be fixed now but if you discover any more arrow functions behaving weird, please let me know!