-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathDowngradeReadonlyClassManipulator.php
More file actions
89 lines (72 loc) · 2.27 KB
/
DowngradeReadonlyClassManipulator.php
File metadata and controls
89 lines (72 loc) · 2.27 KB
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
<?php
declare(strict_types=1);
namespace Rector\DowngradePhp82\NodeManipulator;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Privatization\NodeManipulator\VisibilityManipulator;
use Rector\ValueObject\MethodName;
final readonly class DowngradeReadonlyClassManipulator
{
public function __construct(
private VisibilityManipulator $visibilityManipulator
) {
}
public function process(Class_ $class): ?Class_
{
if (! $this->visibilityManipulator->isReadonly($class)) {
return null;
}
$this->visibilityManipulator->removeReadonly($class);
$this->makePropertiesReadonly($class);
$this->makePromotedPropertiesReadonly($class);
return $class;
}
private function makePropertiesReadonly(Class_ $class): void
{
foreach ($class->getProperties() as $property) {
if ($property->isReadonly()) {
continue;
}
/**
* It technically impossible that readonly class has:
*
* - non-typed property
* - static property
*
* but here to ensure no flip-flop when using direct rule for multiple rules applied
*/
if ($property->type === null) {
continue;
}
if ($property->isStatic()) {
continue;
}
$this->visibilityManipulator->makeReadonly($property);
}
}
private function makePromotedPropertiesReadonly(Class_ $class): void
{
$classMethod = $class->getMethod(MethodName::CONSTRUCT);
if (! $classMethod instanceof ClassMethod) {
return;
}
foreach ($classMethod->getParams() as $param) {
if ($this->visibilityManipulator->isReadonly($param)) {
continue;
}
/**
* not property promotion, just param
*/
if ($param->flags === 0) {
continue;
}
/**
* also not typed, just param
*/
if ($param->type === null) {
continue;
}
$this->visibilityManipulator->makeReadonly($param);
}
}
}