rector/src/Rector/Function_/FunctionReplaceRector.php

89 lines
2.3 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
namespace Rector\Rector\Function_;
use PhpParser\Node;
2018-12-31 00:10:56 +00:00
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name\FullyQualified;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\ConfiguredCodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class FunctionReplaceRector extends AbstractRector
{
/**
* @var string[]|string[][]
*/
private $oldFunctionToNewFunction = [];
/**
* @param string[]|string[][] $oldFunctionToNewFunction
*/
public function __construct(array $oldFunctionToNewFunction)
{
2018-10-22 17:39:10 +00:00
$this->oldFunctionToNewFunction = $oldFunctionToNewFunction;
}
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Turns defined function call new one.', [
new ConfiguredCodeSample(
'view("...", []);',
'Laravel\Templating\render("...", []);',
[
'view' => 'Laravel\Templating\render',
]
),
]);
}
/**
2018-08-14 22:12:41 +00:00
* @return string[]
*/
2018-08-14 22:12:41 +00:00
public function getNodeTypes(): array
{
2018-08-14 22:12:41 +00:00
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
2018-10-22 17:39:10 +00:00
foreach ($this->oldFunctionToNewFunction as $oldFunction => $newFunction) {
if (! $this->isNameInsensitive($node, $oldFunction)) {
continue;
}
2018-12-31 00:10:56 +00:00
// rename of function into wrap function
// e.g. one($arg) → three(two($agr));
if (is_array($newFunction)) {
return $this->wrapFuncCalls($node, $newFunction);
}
2018-10-22 17:39:10 +00:00
$node->name = new FullyQualified($newFunction);
}
return $node;
}
2018-12-31 00:10:56 +00:00
/**
* @param string[] $newFunctions
*/
private function wrapFuncCalls(FuncCall $funcCallNode, array $newFunctions): FuncCall
{
$previousNode = null;
$newFunctions = array_reverse($newFunctions);
foreach ($newFunctions as $wrapFunction) {
$arguments = $previousNode === null ? $funcCallNode->args : [new Arg($previousNode)];
2018-12-31 00:10:56 +00:00
$funcCallNode = new FuncCall(new FullyQualified($wrapFunction), $arguments);
$previousNode = $funcCallNode;
}
return $funcCallNode;
}
}