Skip to content

Commit

Permalink
[DeadCode] Skip remove variable on switch use return after break on R…
Browse files Browse the repository at this point in the history
…emoveUnusedVariableAssignRector (#2145)

* [DeadCode] Skip remove on switch use return after break on RemoveUnusedVariableAssignRector

* Fixed 🎉

* check against RemoveUnreachableStatementRector which remove the return after break

* rename fixture

* rename fixture

* eol
  • Loading branch information
samsonasik committed Apr 24, 2022
1 parent 55807fa commit dc7a9a8
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

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

final class SkipRemoveVariableOnNextReturnAfterBreakInCase
{
public function run($a)
{
switch ($a)
{
case 'A':
$x = 'a';
break;
return;
}

echo $x;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector\Fixture;

final class SwitchReturnAfterBreak
{
public function run($a)
{
switch ($a)
{
case 'A':
$x = 'a';
break;
return;
}

echo $x;
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector\Fixture;

final class SwitchReturnAfterBreak
{
public function run($a)
{
switch ($a)
{
case 'A':
$x = 'a';
break;
}

echo $x;
}
}

?>
6 changes: 5 additions & 1 deletion src/PhpParser/Node/BetterNodeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
Expand Down Expand Up @@ -366,7 +367,10 @@ public function findFirstNext(Node $node, callable $filter): ?Node
$next = $node->getAttribute(AttributeKey::NEXT_NODE);
if ($next instanceof Node) {
if ($next instanceof Return_ && $next->expr === null) {
return null;
$parent = $node->getAttribute(AttributeKey::PARENT_NODE);
if (! $parent instanceof Case_) {
return null;
}
}

$found = $this->findFirst($next, $filter);
Expand Down

0 comments on commit dc7a9a8

Please sign in to comment.