rector/src/Rector/MethodCall/MethodNameReplacerRector.php

88 lines
2.1 KiB
PHP
Raw Normal View History

2017-10-06 11:57:21 +00:00
<?php declare(strict_types=1);
namespace Rector\Rector\MethodCall;
2017-10-06 11:57:21 +00:00
use PhpParser\Node;
use PhpParser\Node\Identifier;
use Rector\NodeTypeResolver\Node\Attribute;
2017-10-06 11:57:21 +00:00
use Rector\Rector\AbstractRector;
2018-08-01 19:52:44 +00:00
use Rector\RectorDefinition\ConfiguredCodeSample;
2018-04-08 11:51:26 +00:00
use Rector\RectorDefinition\RectorDefinition;
2017-10-06 11:57:21 +00:00
final class MethodNameReplacerRector extends AbstractRector
{
/**
* class => [
* oldMethod => newMethod
* ]
*
* @var string[][]
*/
2018-10-22 17:17:17 +00:00
private $oldToNewMethodsByClass = [];
2017-10-06 11:57:21 +00:00
/**
2018-10-22 17:17:17 +00:00
* @param string[][] $oldToNewMethodsByClass
*/
2018-10-22 17:17:17 +00:00
public function __construct(array $oldToNewMethodsByClass)
{
$this->oldToNewMethodsByClass = $oldToNewMethodsByClass;
2017-10-06 11:57:21 +00:00
}
2018-04-08 11:51:26 +00:00
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Turns method names to new ones.', [
2018-08-01 19:52:44 +00:00
new ConfiguredCodeSample(
2018-04-08 11:51:26 +00:00
<<<'CODE_SAMPLE'
2018-10-22 17:17:17 +00:00
$someObject = new SomeExample;
2018-04-09 12:48:15 +00:00
$someObject->oldMethod();
2018-04-08 11:51:26 +00:00
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
2018-10-22 17:17:17 +00:00
$someObject = new SomeExample;
2018-04-09 12:48:15 +00:00
$someObject->newMethod();
2018-04-08 11:51:26 +00:00
CODE_SAMPLE
2018-08-01 19:52:44 +00:00
,
[
'$perClassOldToNewMethods' => [
2018-10-22 17:17:17 +00:00
'SomeExampleClass' => [
2018-08-01 19:52:44 +00:00
'oldMethod' => 'newMethod',
],
],
]
),
2018-04-08 11:51:26 +00:00
]);
}
2018-08-14 22:12:41 +00:00
/**
* @return string[]
*/
public function getNodeTypes(): array
2017-10-06 11:57:21 +00:00
{
2018-10-22 17:17:17 +00:00
return [Identifier::class];
2017-10-06 11:57:21 +00:00
}
/**
2018-10-22 17:17:17 +00:00
* @param Identifier $node
2017-10-06 11:57:21 +00:00
*/
public function refactor(Node $node): ?Node
{
$parentNode = $node->getAttribute(Attribute::PARENT_NODE);
2018-10-22 17:17:17 +00:00
foreach ($this->oldToNewMethodsByClass as $type => $oldToNewMethods) {
if (! $this->isType($parentNode, $type)) {
continue;
}
2018-08-14 22:12:41 +00:00
2018-10-22 17:17:17 +00:00
foreach ($oldToNewMethods as $oldMethod => $newMethod) {
2018-10-22 17:36:12 +00:00
if (! $this->isNameInsensitive($node, $oldMethod)) {
2018-10-22 17:17:17 +00:00
continue;
}
2018-08-14 22:12:41 +00:00
2018-10-22 17:17:17 +00:00
$node->name = $newMethod;
}
2018-08-14 22:12:41 +00:00
}
return $node;
}
2017-10-06 11:57:21 +00:00
}