rector/packages/Renaming/src/Rector/Function_/RenameFunctionRector.php

96 lines
2.6 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
namespace Rector\Renaming\Rector\Function_;
2019-02-19 15:56:41 +00:00
use Nette\Utils\Strings;
use PhpParser\Node;
2018-12-31 00:10:56 +00:00
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
2019-02-19 15:56:41 +00:00
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\ConfiguredCodeSample;
use Rector\RectorDefinition\RectorDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Rector\Function_\RenameFunctionRector\RenameFunctionRectorTest
*/
final class RenameFunctionRector 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) {
2019-08-25 10:37:56 +00:00
if (! $this->isName($node, $oldFunction)) {
2018-10-22 17:39:10 +00:00
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);
}
2019-02-27 13:21:11 +00:00
$node->name = Strings::contains($newFunction, '\\') ? new FullyQualified($newFunction) : new Name(
$newFunction
);
2018-10-22 17:39:10 +00:00
}
return $node;
}
2018-12-31 00:10:56 +00:00
/**
* @param string[] $newFunctions
*/
2019-02-22 17:25:31 +00:00
private function wrapFuncCalls(FuncCall $funcCall, array $newFunctions): FuncCall
2018-12-31 00:10:56 +00:00
{
$previousNode = null;
$newFunctions = array_reverse($newFunctions);
foreach ($newFunctions as $wrapFunction) {
2019-02-22 17:25:31 +00:00
$arguments = $previousNode === null ? $funcCall->args : [new Arg($previousNode)];
2018-12-31 00:10:56 +00:00
2019-02-22 17:25:31 +00:00
$funcCall = new FuncCall(new FullyQualified($wrapFunction), $arguments);
$previousNode = $funcCall;
2018-12-31 00:10:56 +00:00
}
2019-02-22 17:25:31 +00:00
return $funcCall;
2018-12-31 00:10:56 +00:00
}
}