diff --git a/rules-tests/Php72/Rector/While_/WhileEachToForeachRector/Fixture/trailing_comma_last.php.inc b/rules-tests/Php72/Rector/While_/WhileEachToForeachRector/Fixture/trailing_comma_last.php.inc new file mode 100644 index 00000000000..69955633cc6 --- /dev/null +++ b/rules-tests/Php72/Rector/While_/WhileEachToForeachRector/Fixture/trailing_comma_last.php.inc @@ -0,0 +1,34 @@ + +----- + diff --git a/rules/Php72/Rector/While_/WhileEachToForeachRector.php b/rules/Php72/Rector/While_/WhileEachToForeachRector.php index 44564a6ddd8..42340f5b0fd 100644 --- a/rules/Php72/Rector/While_/WhileEachToForeachRector.php +++ b/rules/Php72/Rector/While_/WhileEachToForeachRector.php @@ -113,8 +113,16 @@ public function refactor(Node $node): ?Node [$eachFuncCall->args[0]] ) : $eachFuncCall->args[0]->value; - /** @var ArrayItem $arrayItem */ $arrayItem = array_pop($listNode->items); + $isTrailingCommaLast = false; + if (! $arrayItem instanceof ArrayItem) { + $foreachedExpr = $this->nodeFactory->createFuncCall('array_keys', [$eachFuncCall->args[0]]); + /** @var ArrayItem $arrayItem */ + $arrayItem = current($listNode->items); + + $isTrailingCommaLast = true; + } + $foreach = new Foreach_($foreachedExpr, $arrayItem, [ 'stmts' => $node->stmts, ]); @@ -126,7 +134,7 @@ public function refactor(Node $node): ?Node /** @var ArrayItem|null $keyItem */ $keyItem = array_pop($listNode->items); - if ($keyItem !== null) { + if ($keyItem !== null && ! $isTrailingCommaLast) { $foreach->keyVar = $keyItem->value; } }