Skip to content

Commit

Permalink
Fix false-positive unused variable (#17)
Browse files Browse the repository at this point in the history
Close #16
  • Loading branch information
Slamdunk authored Aug 22, 2019
1 parent 38502e6 commit 15589b5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
13 changes: 6 additions & 7 deletions lib/UnusedVariableRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
namespace SlamPhpStan;

use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Scalar\String_;
Expand Down Expand Up @@ -96,15 +94,16 @@ private function gatherVariablesUsage(Node $node, array & $unusedVariables, arra
if (\is_string($node->var->name) && ! isset($parameters[$node->var->name]) && ! isset(self::$globalVariables[$node->var->name])) {
$unusedVariables[$node->var->name] = $node->var;
}
} elseif ($node->var instanceof PropertyFetch) {
$this->gatherVariablesUsage($node->var->var, $unusedVariables, $usedVariables, $parameters);
} elseif ($node->var instanceof ArrayDimFetch) {
if ($node->var->var instanceof Node) {
} else {
if (\property_exists($node->var, 'var') && $node->var->var instanceof Node) {
$this->gatherVariablesUsage($node->var->var, $unusedVariables, $usedVariables, $parameters);
}
if ($node->var->dim instanceof Node) {
if (\property_exists($node->var, 'dim') && $node->var->dim instanceof Node) {
$this->gatherVariablesUsage($node->var->dim, $unusedVariables, $usedVariables, $parameters);
}
if (\property_exists($node->var, 'name') && $node->var->name instanceof Node) {
$this->gatherVariablesUsage($node->var->name, $unusedVariables, $usedVariables, $parameters);
}
}
}
if ($node instanceof Variable) {
Expand Down
22 changes: 22 additions & 0 deletions tests/TestAsset/UnusedVariableRule/fixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,26 @@ function foo($ref)
$GLOBALS = null;
}

class Test
{
function foo(array $numVals)
{
$arr = [
"1" => "propOne",
"2" => "propTwo",
];

foreach ($numVals as $num => $v) {
$key = $arr[$num];
$this->{$key} = $v;

$key2 = $arr[$num];
$this->{$key2}();

$this->key = 1;
$this->key2();
}
}
}

$outsideFunctionVar = 1;

0 comments on commit 15589b5

Please sign in to comment.