Skip to content

Commit

Permalink
skip variable if used as next
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jul 3, 2022
1 parent 6da5c41 commit 113513a
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Rector\Tests\DeadCode\Rector\StmtsAwareInterface\RemoveJustVariableAssignRector\Fixture;

final class SkipUsedLater
{
private int $temporaryValue;

public function run()
{
$result = 100;

$this->temporaryValue = $result;

if ($result === 100) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ public function refactor(Node $node): ?Node

$currentAssign = $stmt->expr;


if (! $nextStmt instanceof Expression) {
continue;
}
Expand All @@ -105,7 +104,7 @@ public function refactor(Node $node): ?Node
continue;
}

if (! $this->areTwoVariablesCrossAssign($currentAssign, $nextAssign)) {
if (! $this->areTwoVariablesCrossAssign($currentAssign, $nextAssign, $node)) {
continue;
}

Expand All @@ -128,9 +127,14 @@ public function refactor(Node $node): ?Node
*
* $<some> = 1000;
* $this->value = $<some>;
*
* + not used $<some> bellow, so removal will not break it
*/
private function areTwoVariablesCrossAssign(Assign $currentAssign, Assign $nextAssign): bool
{
private function areTwoVariablesCrossAssign(
Assign $currentAssign,
Assign $nextAssign,
StmtsAwareInterface $stmtsAware
): bool {
// is just re-assign to variable
if (! $currentAssign->var instanceof Variable) {
return false;
Expand All @@ -148,7 +152,31 @@ private function areTwoVariablesCrossAssign(Assign $currentAssign, Assign $nextA
return false;
}

return ! $this->variableAnalyzer->isUsedByReference($nextAssign->expr);
if ($this->variableAnalyzer->isUsedByReference($nextAssign->expr)) {
return false;
}

$currentVariable = $currentAssign->var;
$nextVariable = $nextAssign->expr;

// is variable used later?
$nextUsedVariable = $this->betterNodeFinder->findFirst($stmtsAware, function (\PhpParser\Node $node) use (
$currentVariable,
$nextVariable
) {
if (in_array($node, [$currentVariable, $nextVariable], true)) {
return false;
}

if (! $node instanceof Variable) {
return false;
}

// is variable name?
return $this->nodeNameResolver->areNamesEqual($node, $currentVariable);
});

return ! $nextUsedVariable instanceof Variable;
}

/**
Expand Down

0 comments on commit 113513a

Please sign in to comment.