-
-
Notifications
You must be signed in to change notification settings - Fork 688
/
RenameAttributeRector.php
94 lines (92 loc) · 2.8 KB
/
RenameAttributeRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare (strict_types=1);
namespace Rector\Renaming\Rector\Class_;
use PhpParser\Node;
use PhpParser\Node\Attribute;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\Rector\AbstractRector;
use Rector\Renaming\ValueObject\RenameAttribute;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix202501\Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Renaming\Rector\Class_\RenameAttributeRector\RenameAttributeRectorTest
*/
final class RenameAttributeRector extends AbstractRector implements ConfigurableRectorInterface, MinPhpVersionInterface
{
/**
* @var RenameAttribute[]
*/
private array $renameAttributes = [];
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Rename attribute class names', [new ConfiguredCodeSample(<<<'CODE_SAMPLE'
#[SimpleRoute()]
class SomeClass
{
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
#[BasicRoute()]
class SomeClass
{
}
CODE_SAMPLE
, [new RenameAttribute('SimpleRoute', 'BasicRoute')])]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [Class_::class, ClassMethod::class, Property::class];
}
/**
* @param Class_|ClassMethod|Property $node
*/
public function refactor(Node $node) : ?Node
{
$hasChanged = \false;
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$newAttributeName = $this->matchNewAttributeName($attr);
if (!\is_string($newAttributeName)) {
continue;
}
$attr->name = new FullyQualified($newAttributeName);
$hasChanged = \true;
}
}
if ($hasChanged) {
return $node;
}
return null;
}
/**
* @param mixed[] $configuration
*/
public function configure(array $configuration) : void
{
Assert::allIsAOf($configuration, RenameAttribute::class);
$this->renameAttributes = $configuration;
}
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::ATTRIBUTES;
}
private function matchNewAttributeName(Attribute $attribute) : ?string
{
foreach ($this->renameAttributes as $renameAttribute) {
if ($this->isName($attribute->name, $renameAttribute->getOldAttribute())) {
return $renameAttribute->getNewAttribute();
}
}
return null;
}
}