sirbrillig / phpcs-variable-analysis

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

Do not close scope of ref reassignment when inside else #306

Closed sirbrillig closed 1 year ago

sirbrillig commented 1 year ago

When we reassign a reference variable, we need to know if it has been used first. This is because changing the reference of a variable is like creating a new variable; if its previous value was never used, then we should report an unused variable.

For example, this is the intended behavior:

$foo = &$bar;  // Warning that $foo is unused because once it is reassigned, it is a different variable.
$foo = &$yaz;
echo $foo;

However, because conditional statements might or might not be run, we must assume that assignments by reference might not happen and should not trigger a warning even if it appears they are unused.

This example reassignment should not trigger a warning:

$foo = &$bar; // No warning because we cannot be sure that the next assignment will happen.
if ( $x ) {
  $foo = &$yaz;
}
echo $foo;

This logic already exists, but before this PR it does not apply to else blocks or elseif blocks, only if.

For example, this code should not trigger a warning, but it does before this PR:

if ( $x ) {
  $foo = &$bar; // No warning because we cannot be sure that the 'else' assignment will happen.
} else {
  $foo = &$yaz;
}
echo $foo;

In this PR we extend that logic to also cover else and elseif.

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