forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClassConstFetchToValueRector.php
88 lines (74 loc) · 2.67 KB
/
ClassConstFetchToValueRector.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
<?php
declare(strict_types=1);
namespace Rector\Transform\Rector\ClassConstFetch;
use PhpParser\BuilderHelpers;
use PhpParser\Node;
use PhpParser\Node\Expr\ClassConstFetch;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Transform\ValueObject\ClassConstFetchToValue;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;
/**
* @see \Rector\Tests\Transform\Rector\ClassConstFetch\ClassConstFetchToValueRector\ClassConstFetchToValueRectorTest
*/
final class ClassConstFetchToValueRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var string
*/
public const CLASS_CONST_FETCHES_TO_VALUES = 'old_constants_to_new_valuesByType';
/**
* @var ClassConstFetchToValue[]
*/
private $classConstFetchesToValues = [];
public function getRuleDefinition(): RuleDefinition
{
$configuration = [
self::CLASS_CONST_FETCHES_TO_VALUES => [
new ClassConstFetchToValue('Nette\Configurator', 'DEVELOPMENT', 'development'),
new ClassConstFetchToValue('Nette\Configurator', 'PRODUCTION', 'production'),
],
];
return new RuleDefinition('Replaces constant by value', [
new ConfiguredCodeSample(
'$value === Nette\Configurator::DEVELOPMENT',
'$value === "development"',
$configuration
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassConstFetch::class];
}
/**
* @param ClassConstFetch $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->classConstFetchesToValues as $classConstFetchToValue) {
if (! $this->isObjectType($node->class, $classConstFetchToValue->getObjectType())) {
continue;
}
if (! $this->isName($node->name, $classConstFetchToValue->getConstant())) {
continue;
}
return BuilderHelpers::normalizeValue($classConstFetchToValue->getValue());
}
return $node;
}
/**
* @param array<string, ClassConstFetchToValue[]> $configuration
*/
public function configure(array $configuration): void
{
$classConstFetchesToValues = $configuration[self::CLASS_CONST_FETCHES_TO_VALUES] ?? [];
Assert::allIsInstanceOf($classConstFetchesToValues, ClassConstFetchToValue::class);
$this->classConstFetchesToValues = $classConstFetchesToValues;
}
}