Skip to content

Commit

Permalink
[CodeQuality] Skip deep append in if foreach before on ForeachItemsAs…
Browse files Browse the repository at this point in the history
…signToEmptyArrayToAssignRector (#4053)
  • Loading branch information
samsonasik committed Jun 3, 2023
1 parent 069e53a commit c9fc74b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector\Fixture;

class SkipDeepAppendForeach
{
public function run(array $items)
{
$items2 = [];

if (rand(0, 1)) {
foreach (['foo', 'bar'] as $item) {
$items2[] = $item;
}
}

foreach ($items as $item) {
$items2[] = $item;
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,11 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node
$emptyArrayVariables[] = $variableName;
}

if ($this->isAppend($stmt, $emptyArrayVariables)) {
return null;
}

if (! $stmt instanceof Foreach_) {
if ($this->isAppend($stmt, $emptyArrayVariables)) {
return null;
}

continue;
}

Expand Down Expand Up @@ -128,10 +128,6 @@ private function isAppend(Stmt $stmt, array $emptyArrayVariables): bool
$this->traverseNodesWithCallable(
$stmt,
function (Node $subNode) use ($emptyArrayVariables, &$isAppend): ?int {
if ($subNode instanceof Foreach_) {
return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}

if ($subNode instanceof Assign && $subNode->var instanceof ArrayDimFetch) {
$isAppend = $this->isNames($subNode->var->var, $emptyArrayVariables);

Expand Down

0 comments on commit c9fc74b

Please sign in to comment.