forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRenamePropertyRector.php
82 lines (70 loc) · 2.33 KB
/
RenamePropertyRector.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
<?php
declare(strict_types=1);
namespace Rector\Renaming\Rector\PropertyFetch;
use PhpParser\Node;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Identifier;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Renaming\ValueObject\RenameProperty;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Renaming\Rector\PropertyFetch\RenamePropertyRector\RenamePropertyRectorTest
*/
final class RenamePropertyRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var string
*/
public const RENAMED_PROPERTIES = 'old_to_new_property_by_types';
/**
* @var RenameProperty[]
*/
private $renamedProperties = [];
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Replaces defined old properties by new ones.', [
new ConfiguredCodeSample(
'$someObject->someOldProperty;',
'$someObject->someNewProperty;',
[
self::RENAMED_PROPERTIES => [
new RenameProperty('SomeClass', 'someOldProperty', 'someNewProperty'),
],
]
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [PropertyFetch::class];
}
/**
* @param PropertyFetch $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->renamedProperties as $renamedProperty) {
if (! $this->isObjectType($node->var, $renamedProperty->getObjectType())) {
continue;
}
if (! $this->isName($node, $renamedProperty->getOldProperty())) {
continue;
}
$node->name = new Identifier($renamedProperty->getNewProperty());
return $node;
}
return null;
}
public function configure(array $configuration): void
{
$renamedProperties = $configuration[self::RENAMED_PROPERTIES] ?? [];
Assert::allIsInstanceOf($renamedProperties, RenameProperty::class);
$this->renamedProperties = $renamedProperties;
}
}