Skip to content

Commit 6a1aa20

Browse files
samsonasikjtojnar
andauthored
[DeadCode] Skip next assign expr has side effect inside try {} on RemoveDoubleAssignRector (#7775)
* [DeadCode] Add test for RemoveDoubleAssignRector with reset before throwing assignment Reproduces rectorphp/rector#9569 * rename fixture * [DeadCode] Skip has side effect inside try {} on RemoveDoubleAssignRector --------- Co-authored-by: Jan Tojnar <[email protected]>
1 parent d1ff945 commit 6a1aa20

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\Assign\RemoveDoubleAssignRector\Fixture;
4+
5+
/** @throws \Exception */
6+
function get_body(): string {
7+
static $i = 0;
8+
9+
var_dump($i);
10+
11+
return $i++ === 0 ? "foo" : throw new \Exception("Failed to get body");
12+
}
13+
14+
foreach ([1, 2, 3] as $value) {
15+
try {
16+
$body = null;
17+
$body = get_body();
18+
var_dump($body);
19+
} catch (\Exception) {
20+
var_dump($body);
21+
}
22+
23+
}
24+
?>

rules/DeadCode/Rector/Assign/RemoveDoubleAssignRector.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use PhpParser\Node\Expr\StaticPropertyFetch;
1111
use PhpParser\Node\Expr\Variable;
1212
use PhpParser\Node\Stmt\Expression;
13+
use PhpParser\Node\Stmt\TryCatch;
1314
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
1415
use Rector\PhpParser\Enum\NodeGroup;
1516
use Rector\PhpParser\Node\BetterNodeFinder;
@@ -110,6 +111,11 @@ public function refactor(Node $node): ?Node
110111
continue;
111112
}
112113

114+
// side effect may throw exception, and may be handled by catch block
115+
if ($node instanceof TryCatch && $this->sideEffectNodeDetector->detectCallExpr($nextAssign->expr)) {
116+
continue;
117+
}
118+
113119
// remove current Stmt if will be overridden in next stmt
114120
unset($node->stmts[$key]);
115121

0 commit comments

Comments
 (0)