Skip to content

Commit

Permalink
[Php72] Handle crash on trailing comma last on WhileEachToForeachRect…
Browse files Browse the repository at this point in the history
…or (#3186)
  • Loading branch information
samsonasik committed Dec 11, 2022
1 parent e479114 commit 802d98e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Rector\Tests\Php72\Rector\While_\WhileEachToForeachRector\Fixture;

// ref https://3v4l.org/mTeIL#v7.1.31 vs https://3v4l.org/UJH9S
final class TrailingCommaLast
{
public function run()
{
while(list($code_name,) = each($poster_xd))
{
$poster_xd[$code_name] = preg_replace($orig_word, $replacement_word, $poster_xd[$code_name]);
}
}
}

?>
-----
<?php

namespace Rector\Tests\Php72\Rector\While_\WhileEachToForeachRector\Fixture;

// ref https://3v4l.org/mTeIL#v7.1.31 vs https://3v4l.org/UJH9S
final class TrailingCommaLast
{
public function run()
{
foreach (array_keys($poster_xd) as $code_name) {
$poster_xd[$code_name] = preg_replace($orig_word, $replacement_word, $poster_xd[$code_name]);
}
}
}

?>
12 changes: 10 additions & 2 deletions rules/Php72/Rector/While_/WhileEachToForeachRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
]);
Expand All @@ -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;
}
}
Expand Down

0 comments on commit 802d98e

Please sign in to comment.