Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Php72] Handle crash on trailing comma last on WhileEachToForeachRector #3186

Merged
merged 3 commits into from
Dec 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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