rector/rules/Renaming/Rector/ConstFetch/RenameConstantRector.php

82 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Renaming\Rector\ConstFetch;
2019-02-19 14:53:31 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Name;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\Rector\AbstractRector;
use Rector\Validation\RectorAssert;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix202403\Webmozart\Assert\Assert;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Renaming\Rector\ConstFetch\RenameConstantRector\RenameConstantRectorTest
2019-09-03 09:11:45 +00:00
*/
final class RenameConstantRector extends AbstractRector implements ConfigurableRectorInterface
2019-02-19 14:53:31 +00:00
{
/**
2021-04-13 16:01:31 +00:00
* @var array<string, string>
2019-02-19 14:53:31 +00:00
*/
2020-07-29 13:55:33 +00:00
private $oldToNewConstants = [];
public function getRuleDefinition() : RuleDefinition
2019-02-19 14:53:31 +00:00
{
return new RuleDefinition('Replace constant by new ones', [new ConfiguredCodeSample(<<<'CODE_SAMPLE'
2019-02-19 14:53:31 +00:00
final class SomeClass
{
public function run()
{
return MYSQL_ASSOC;
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-02-19 14:53:31 +00:00
final class SomeClass
{
public function run()
{
return MYSQLI_ASSOC;
}
}
CODE_SAMPLE
, ['MYSQL_ASSOC' => 'MYSQLI_ASSOC', 'OLD_CONSTANT' => 'NEW_CONSTANT'])]);
2019-02-19 14:53:31 +00:00
}
/**
* @return array<class-string<Node>>
2019-02-19 14:53:31 +00:00
*/
public function getNodeTypes() : array
2019-02-19 14:53:31 +00:00
{
return [ConstFetch::class];
2019-02-19 14:53:31 +00:00
}
/**
* @param ConstFetch $node
2019-02-19 14:53:31 +00:00
*/
public function refactor(Node $node) : ?Node
2019-02-19 14:53:31 +00:00
{
foreach ($this->oldToNewConstants as $oldConstant => $newConstant) {
if (!$this->isName($node->name, $oldConstant)) {
2019-02-19 14:53:31 +00:00
continue;
}
$node->name = new Name($newConstant);
2021-04-13 16:01:31 +00:00
return $node;
2019-02-19 14:53:31 +00:00
}
2021-04-13 16:01:31 +00:00
return null;
2019-02-19 14:53:31 +00:00
}
2021-04-13 16:01:31 +00:00
/**
* @param mixed[] $configuration
2021-04-13 16:01:31 +00:00
*/
public function configure(array $configuration) : void
2020-07-29 13:55:33 +00:00
{
Assert::allString(\array_keys($configuration));
Assert::allString($configuration);
foreach ($configuration as $oldConstant => $newConstant) {
RectorAssert::constantName($oldConstant);
RectorAssert::constantName($newConstant);
}
/** @var array<string, string> $configuration */
$this->oldToNewConstants = $configuration;
2020-07-29 13:55:33 +00:00
}
2019-02-19 14:53:31 +00:00
}