-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathToNativeRector.php
74 lines (62 loc) · 2.14 KB
/
ToNativeRector.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
<?php declare(strict_types=1);
namespace BenSampo\Enum\Rector;
use Illuminate\Support\Arr;
use PhpParser\Node;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\ObjectType;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
/**
* Conversion of enums and their usages can not be done in a single run of Rector,
* that would leave the project partially converted.
* Usages seen after the enum classes have been converted will no longer be transformed.
*
* Thus, we split into two rectors that can be run separately.
*/
abstract class ToNativeRector extends AbstractRector implements ConfigurableRectorInterface
{
/** @var array<ObjectType> */
protected array $classes;
public function __construct(
protected ValueResolver $valueResolver
) {}
/** @param array<class-string> $configuration */
public function configure(array $configuration): void
{
$this->classes = array_map(
static fn (string $class): ObjectType => new ObjectType($class),
$configuration,
);
}
protected function inConfiguredClasses(Node $node): bool
{
// I don't understand why, but get_class(<non-object>) is used in concat: '' . get_class(0)
// Somehow isObjectType produces true - thus leading rector to make this: '' . get_class(ß)->value
if ($this->getType($node) instanceof ConstantBooleanType) {
return false;
}
foreach ($this->classes as $class) {
if ($this->isObjectType($node, $class)) {
return true;
}
}
return false;
}
/** @param array<mixed> $constantValues */
protected function enumScalarType(array $constantValues): ?string
{
if ($constantValues === []) {
return null;
}
// Assume the first constant value has the correct type
$value = Arr::first($constantValues);
if (is_string($value)) {
return 'string';
}
if (is_int($value)) {
return 'int';
}
return null;
}
}