rector/src/Rector/Constant/ClassConstantReplacerRector.php

107 lines
2.8 KiB
PHP
Raw Normal View History

2017-10-20 18:29:23 +00:00
<?php declare(strict_types=1);
namespace Rector\Rector\Constant;
2017-10-20 18:29:23 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Identifier;
use Rector\Builder\IdentifierRenamer;
2017-10-20 18:29:23 +00:00
use Rector\NodeAnalyzer\ClassConstAnalyzer;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\ConfiguredCodeSample;
2018-04-08 11:51:26 +00:00
use Rector\RectorDefinition\RectorDefinition;
2017-10-20 18:29:23 +00:00
final class ClassConstantReplacerRector extends AbstractRector
{
/**
* class => [
* OLD_CONSTANT => NEW_CONSTANT
* ]
*
* @var string[]
*/
private $oldToNewConstantsByClass = [];
/**
* @var ClassConstAnalyzer
*/
private $classConstAnalyzer;
/**
* @var IdentifierRenamer
*/
private $identifierRenamer;
2017-10-20 18:29:23 +00:00
/**
* @param string[] $oldToNewConstantsByClass
*/
public function __construct(
array $oldToNewConstantsByClass,
ClassConstAnalyzer $classConstAnalyzer,
IdentifierRenamer $identifierRenamer
) {
2017-10-20 18:29:23 +00:00
$this->oldToNewConstantsByClass = $oldToNewConstantsByClass;
$this->classConstAnalyzer = $classConstAnalyzer;
$this->identifierRenamer = $identifierRenamer;
2017-10-20 18:29:23 +00:00
}
2018-04-08 11:51:26 +00:00
/**
* @todo complete list with all possibilities
*/
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Replaces defined class constants in their calls.', [
new ConfiguredCodeSample(
'$value = SomeClass::OLD_CONSTANT;',
'$value = SomeClass::NEW_CONSTANT;',
[
'$oldToNewConstantsByClass' => [
'SomeClass' => [
'OLD_CONSTANT' => 'NEW_CONSTANT',
],
],
]
),
2018-04-08 11:51:26 +00:00
]);
}
2018-08-14 22:12:41 +00:00
/**
* @return string[]
*/
public function getNodeTypes(): array
2017-10-20 18:29:23 +00:00
{
2018-08-14 22:12:41 +00:00
return [ClassConstFetch::class];
2017-10-20 18:29:23 +00:00
}
/**
* @param ClassConstFetch $classConstFetchNode
*/
public function refactor(Node $classConstFetchNode): ?Node
{
2018-10-14 10:48:21 +00:00
$activeType = $this->classConstAnalyzer->matchTypes(
$classConstFetchNode,
array_keys($this->oldToNewConstantsByClass)
);
2018-08-14 22:12:41 +00:00
if ($activeType === null) {
return null;
}
$configuration = $this->oldToNewConstantsByClass[$activeType];
2017-12-10 00:28:51 +00:00
/** @var Identifier $identifierNode */
$identifierNode = $classConstFetchNode->name;
$constantName = $identifierNode->toString();
2017-10-20 18:29:23 +00:00
$newConstantName = $configuration[$constantName];
2018-07-25 11:06:07 +00:00
if ($newConstantName === '') {
return $classConstFetchNode;
}
2017-10-20 18:29:23 +00:00
$this->identifierRenamer->renameNode($classConstFetchNode, $newConstantName);
2017-12-25 19:37:09 +00:00
return $classConstFetchNode;
2017-10-20 18:29:23 +00:00
}
}