Skip to content

Commit cad967d

Browse files
authored
Add check for append in foreach items assignment (#7815)
* Add check for append in foreach items assignment * Add test fixture for skipping assignment before conditional foreach
1 parent 13f7abd commit cad967d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector\Fixture;
4+
5+
final class SkipAssignedBeforeInConditionalForeach
6+
{
7+
public function run($data)
8+
{
9+
$list = [];
10+
$groupList = [];
11+
12+
foreach ($data->getItems() as $item) {
13+
if ($item->hasGroup()) {
14+
$groupList[] = ['id' => $item->getGroupId()];
15+
} else {
16+
$list[] = ['id' => $item->getId()];
17+
}
18+
}
19+
20+
foreach ($groupList as $group) {
21+
$list[] = $group;
22+
}
23+
24+
return $list;
25+
}
26+
}

rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,10 @@ public function refactor(Node $node): ?Node
104104
}
105105

106106
if ($this->shouldSkip($stmt, $emptyArrayVariables)) {
107+
if ($this->isAppend($stmt, $emptyArrayVariables)) {
108+
return null;
109+
}
110+
107111
continue;
108112
}
109113

0 commit comments

Comments
 (0)