rector/src/Rector/MethodCall/RenameStaticMethodRector.php

100 lines
2.7 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
namespace Rector\Rector\MethodCall;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\ConfiguredCodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class RenameStaticMethodRector extends AbstractRector
{
/**
2018-10-22 18:12:32 +00:00
* @var string[][]|string[][][]
*/
2018-10-22 18:12:32 +00:00
private $oldToNewMethodByClasses = [];
/**
2018-10-22 18:12:32 +00:00
* @param string[][]|string[][][] $oldToNewMethodByClasses
*/
public function __construct(array $oldToNewMethodByClasses = [])
2018-10-22 18:12:32 +00:00
{
$this->oldToNewMethodByClasses = $oldToNewMethodByClasses;
}
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Turns method names to new ones.', [
2018-10-22 18:12:32 +00:00
new ConfiguredCodeSample(
'SomeClass::oldStaticMethod();',
'AnotherExampleClass::newStaticMethod();',
[
'SomeClass' => [
'oldMethod' => ['AnotherExampleClass', 'newStaticMethod'],
2018-10-22 18:12:32 +00:00
],
]
),
new ConfiguredCodeSample(
'SomeClass::oldStaticMethod();',
'SomeClass::newStaticMethod();',
[
2018-10-22 18:12:32 +00:00
'$oldToNewMethodByClasses' => [
2018-10-15 02:37:09 +00:00
'SomeClass' => [
2018-10-22 18:12:32 +00:00
'oldMethod' => 'newStaticMethod',
],
],
]
),
]);
}
2018-08-14 22:12:41 +00:00
/**
* @return string[]
*/
public function getNodeTypes(): array
{
2018-10-22 18:12:32 +00:00
return [StaticCall::class];
}
/**
2018-10-22 18:12:32 +00:00
* @param StaticCall $node
*/
public function refactor(Node $node): ?Node
{
2018-10-22 18:12:32 +00:00
foreach ($this->oldToNewMethodByClasses as $type => $oldToNewMethods) {
if (! $this->isType($node, $type)) {
continue;
}
2018-10-22 18:12:32 +00:00
foreach ($oldToNewMethods as $oldMethod => $newMethod) {
2019-08-25 10:37:56 +00:00
if (! $this->isName($node, $oldMethod)) {
2018-10-22 18:12:32 +00:00
continue;
}
2018-10-22 18:12:32 +00:00
return $this->rename($node, $newMethod);
}
}
2018-10-22 18:12:32 +00:00
return null;
}
/**
2018-10-22 18:12:32 +00:00
* @param string|string[] $newMethod
*/
2019-02-22 17:25:31 +00:00
private function rename(StaticCall $staticCall, $newMethod): StaticCall
{
2018-10-22 18:12:32 +00:00
if (is_array($newMethod)) {
[$newClass, $newMethod] = $newMethod;
2019-02-22 17:25:31 +00:00
$staticCall->class = new Name($newClass);
$staticCall->name = new Identifier($newMethod);
2018-10-22 18:12:32 +00:00
} else {
2019-02-22 17:25:31 +00:00
$staticCall->name = new Identifier($newMethod);
}
2019-02-22 17:25:31 +00:00
return $staticCall;
}
}