forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringToClassConstantRector.php
97 lines (86 loc) · 2.66 KB
/
StringToClassConstantRector.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
95
96
97
<?php
declare(strict_types=1);
namespace Rector\Transform\Rector\String_;
use PhpParser\Node;
use PhpParser\Node\Scalar\String_;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Transform\ValueObject\StringToClassConstant;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Transform\Rector\String_\StringToClassConstantRector\StringToClassConstantRectorTest
*/
final class StringToClassConstantRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var string
*/
public const STRINGS_TO_CLASS_CONSTANTS = 'strings_to_class_constants';
/**
* @var StringToClassConstant[]
*/
private $stringsToClassConstants = [];
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Changes strings to specific constants', [
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
return ['compiler.post_dump' => 'compile'];
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeSubscriber
{
public static function getSubscribedEvents()
{
return [\Yet\AnotherClass::CONSTANT => 'compile'];
}
}
CODE_SAMPLE
,
[
self::STRINGS_TO_CLASS_CONSTANTS => [
new StringToClassConstant('compiler.post_dump', 'Yet\AnotherClass', 'CONSTANT'),
],
]
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [String_::class];
}
/**
* @param String_ $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->stringsToClassConstants as $stringToClassConstant) {
if (! $this->valueResolver->isValue($node, $stringToClassConstant->getString())) {
continue;
}
return $this->nodeFactory->createClassConstFetch(
$stringToClassConstant->getClass(),
$stringToClassConstant->getConstant()
);
}
return $node;
}
public function configure(array $configuration): void
{
$stringToClassConstants = $configuration[self::STRINGS_TO_CLASS_CONSTANTS] ?? [];
Assert::allIsInstanceOf($stringToClassConstants, StringToClassConstant::class);
$this->stringsToClassConstants = $stringToClassConstants;
}
}