sirbrillig / phpcs-variable-analysis

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

Unused function parameter in lambda function #295

Closed ghnp5 closed 1 year ago

ghnp5 commented 1 year ago

Consider this code:

$type = in_array_cb($_GET['type'], TYPES, fn(&$array, $needle) => $array[2] === $needle);

The parameter $needle is marked as an error:

Unused function parameter $needle.PHPCS(VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)

image
sirbrillig commented 1 year ago

Interesting! It looks like something to do with the array access which is breaking this. The bug does occur in the expression:

do_something(fn($array, $needle) => $array[2] === $needle);

But it does not occur in:

do_something(fn($array, $needle) => $array === $needle);

I think that there's a bug in how we detect the scope of an arrow function which contains a bracket.

sirbrillig commented 1 year ago

https://github.com/sirbrillig/phpcs-variable-analysis/pull/296 should fix this.

ghnp5 commented 1 year ago

Thanks @sirbrillig - that was a quick fix & release!! Working perfectly now.

sirbrillig commented 1 year ago

Turns out the fix was really easy: just stop letting phpcs do its own scope detection for arrow functions. 😁