sirbrillig / phpcs-variable-analysis

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

Fix function call detection to exclude non-function tokens #279

Closed sirbrillig closed 2 years ago

sirbrillig commented 2 years ago

The helper function getFunctionIndexForFunctionCallArgument() (and by association isTokenInsideFunctionCallArgument()) tries to return the position of the function name token for a function call argument (eg: in the expression greet($user) it would return the token position for greet for the variable $user). It does this by finding the nearest enclosing parentheses and then looking at the non-whitespace token that comes before it. If that token does not look like a function definition, then it assumes it is a function call.

Unfortunately, this is too naive and will consider things like equals signs as function calls.

In this PR we modify the function to also reject anything not in PHPCS's list of valid function call token types and anything not in the same scope level.

Fixing this also fixed another bug, which had not been caught because one of the for loop tests was mis-written. Some variables inside for loops were being considered reads as well as writes.

Fixes https://github.com/sirbrillig/phpcs-variable-analysis/issues/277