rector/packages/Php/src/Rector/Each/WhileEachToForeachRector.php

115 lines
2.8 KiB
PHP
Raw Normal View History

2018-10-03 13:14:08 +00:00
<?php declare(strict_types=1);
namespace Rector\Php\Rector\Each;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\List_;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\While_;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
/**
* @source https://wiki.php.net/rfc/deprecations_php_7_2#each
*/
final class WhileEachToForeachRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition(
'each() function is deprecated, use foreach() instead.',
[
new CodeSample(
<<<'CODE_SAMPLE'
while (list($key, $callback) = each($callbacks)) {
// ...
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
foreach ($callbacks as $key => $callback) {
// ...
}
CODE_SAMPLE
),
new CodeSample(
<<<'CODE_SAMPLE'
while (list($key) = each($callbacks)) {
// ...
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
foreach (array_keys($callbacks) as $key) {
// ...
}
CODE_SAMPLE
),
]
);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [While_::class];
}
/**
* @param While_ $node
2018-10-03 13:14:08 +00:00
*/
public function refactor(Node $node): ?Node
2018-10-03 13:14:08 +00:00
{
if (! $node->cond instanceof Assign) {
return null;
2018-10-03 13:14:08 +00:00
}
/** @var Assign $assignNode */
$assignNode = $node->cond;
2018-10-03 13:14:08 +00:00
if (! $this->isListToEachAssign($assignNode)) {
return null;
2018-10-03 13:14:08 +00:00
}
/** @var FuncCall $eachFuncCall */
$eachFuncCall = $assignNode->expr;
/** @var List_ $listNode */
$listNode = $assignNode->var;
2019-02-27 13:21:11 +00:00
$foreachedExpr = count($listNode->items) === 1 ? $this->createFunction(
'array_keys',
[$eachFuncCall->args[0]]
) : $eachFuncCall->args[0]->value;
2018-10-03 13:14:08 +00:00
/** @var ArrayItem $valueItem */
$valueItem = array_pop($listNode->items);
$foreachNode = new Foreach_($foreachedExpr, $valueItem, [
'stmts' => $node->stmts,
2018-10-03 13:14:08 +00:00
]);
// is key included? add it to foreach
2019-02-17 14:12:47 +00:00
if (count($listNode->items) > 0) {
2018-10-03 13:14:08 +00:00
/** @var ArrayItem $keyItem */
$keyItem = array_pop($listNode->items);
$foreachNode->keyVar = $keyItem->value;
}
return $foreachNode;
}
2019-02-22 17:25:31 +00:00
private function isListToEachAssign(Assign $assign): bool
2018-10-03 13:14:08 +00:00
{
2019-02-22 17:25:31 +00:00
if (! $assign->var instanceof List_) {
2018-10-03 13:14:08 +00:00
return false;
}
2019-02-22 17:25:31 +00:00
return $assign->expr instanceof FuncCall && $this->isName($assign->expr, 'each');
2018-10-03 13:14:08 +00:00
}
}