Skip to content

Commit

Permalink
[DeadCode] Skip RemoveUnusedAssignVariableRector on used after if else (
Browse files Browse the repository at this point in the history
#213)

Co-authored-by: GitHub Action <action@github.com>
  • Loading branch information
samsonasik and actions-user committed Jun 13, 2021
1 parent 6888049 commit 5fd67ab
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedAssignVariableRector\Fixture;

class SkipUsedAfterIfElse {
function test() {
if ( true ) {
$test1 = '123';
$test2 = '123';
} else {
$test1 = 'abc';
$test2 = 'abc';
}

echo $test1 . $test2;
}
}

?>
21 changes: 17 additions & 4 deletions rules/DeadCode/Rector/Assign/RemoveUnusedAssignVariableRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\If_;
use PHPStan\Analyser\Scope;
use Rector\Core\Rector\AbstractRector;
use Rector\DeadCode\NodeFinder\NextVariableUsageNodeFinder;
Expand Down Expand Up @@ -101,12 +103,13 @@ public function refactor(Node $node): ?Node

private function shouldSkipAssign(Assign $assign): bool
{
if (! $assign->var instanceof Variable) {
$variable = $assign->var;
if (! $variable instanceof Variable) {
return true;
}

// unable to resolve name
$variableName = $this->getName($assign->var);
$variableName = $this->getName($variable);
if ($variableName === null) {
return true;
}
Expand All @@ -115,8 +118,18 @@ private function shouldSkipAssign(Assign $assign): bool
return true;
}

$nextUsedVariable = $this->nextVariableUsageNodeFinder->find($assign);
return $nextUsedVariable !== null;
$parentIf = $this->betterNodeFinder->findParentType($assign, If_::class);
if (! $parentIf instanceof If_) {
return (bool) $this->nextVariableUsageNodeFinder->find($assign);
}
if (! $parentIf->else instanceof Else_) {
return (bool) $this->nextVariableUsageNodeFinder->find($assign);
}

return (bool) $this->betterNodeFinder->findFirstNext(
$parentIf,
fn (Node $node): bool => $this->nodeComparator->areNodesEqual($node, $variable)
);
}

private function isVariableTypeInScope(Assign $assign): bool
Expand Down

0 comments on commit 5fd67ab

Please sign in to comment.