Skip to content

Commit 07d1687

Browse files
authored
[DeadCode] Skip foreach over side-effecting expression in RemoveDeadIfForeachForRector (#8106)
1 parent 2d0e0f1 commit 07d1687

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

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\For_\RemoveDeadIfForeachForRector\Fixture;
4+
5+
class SkipForeachOverCallSideEffect
6+
{
7+
private $result;
8+
9+
public function run()
10+
{
11+
if (! isset($this->result)) {
12+
foreach ($this->events() as $event) {
13+
}
14+
}
15+
16+
return $this->result;
17+
}
18+
19+
private function events(): iterable
20+
{
21+
$this->result = 1;
22+
yield 1;
23+
}
24+
}

‎rules/DeadCode/Rector/For_/RemoveDeadIfForeachForRector.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,11 @@ private function processForForeach(For_|Foreach_ $for, int $key, Node $stmtsAwar
166166
return;
167167
}
168168

169+
// the iterated expression itself may have side effects, e.g. foreach (generator() as $event) {}
170+
if ($this->hasNodeSideEffect($for->expr)) {
171+
return;
172+
}
173+
169174
$exprs = [$for->expr, $for->valueVar, $for->valueVar];
170175
$variables = $this->betterNodeFinder->findInstanceOf($exprs, Variable::class);
171176
foreach ($variables as $variable) {

0 commit comments

Comments
 (0)