|
9 | 9 | use Rector\Core\NodeAnalyzer\ClassAnalyzer;
|
10 | 10 | use Rector\Core\Rector\AbstractRector;
|
11 | 11 | use Rector\Core\ValueObject\PhpVersionFeature;
|
| 12 | +use Rector\Core\ValueObject\Visibility; |
| 13 | +use Rector\Privatization\NodeManipulator\VisibilityManipulator; |
12 | 14 | use Rector\VersionBonding\Contract\MinPhpVersionInterface;
|
13 | 15 | use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
14 | 16 | use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
|
20 | 22 | */
|
21 | 23 | final class ReadOnlyClassRector extends AbstractRector implements MinPhpVersionInterface
|
22 | 24 | {
|
23 |
| - public function __construct(private readonly ClassAnalyzer $classAnalyzer) |
| 25 | + public function __construct( |
| 26 | + private readonly ClassAnalyzer $classAnalyzer, |
| 27 | + private readonly VisibilityManipulator $visibilityManipulator |
| 28 | + ) |
24 | 29 | {
|
25 | 30 | }
|
26 | 31 |
|
@@ -65,21 +70,34 @@ public function getNodeTypes(): array
|
65 | 70 | */
|
66 | 71 | public function refactor(Node $node): ?Node
|
67 | 72 | {
|
68 |
| - if ($this->classAnalyzer->isAnonymousClass($node)) { |
| 73 | + if ($this->shouldSkip($node)) { |
69 | 74 | return null;
|
70 | 75 | }
|
71 | 76 |
|
| 77 | + $this->visibilityManipulator->changeNodeVisibility($node, Visibility::READONLY); |
| 78 | + |
| 79 | + // update all properties, both in defined property or in property promotino to not readonly, as class already readonly |
| 80 | + |
| 81 | + return $node; |
| 82 | + } |
| 83 | + |
| 84 | + private function shouldSkip(Class_ $node): bool |
| 85 | + { |
| 86 | + if ($this->classAnalyzer->isAnonymousClass($node)) { |
| 87 | + return true; |
| 88 | + } |
| 89 | + |
72 | 90 | $properties = $node->getProperties();
|
73 | 91 | foreach ($properties as $property) {
|
74 | 92 | if (! $property->isReadonly()) {
|
75 |
| - return null; |
| 93 | + return true; |
76 | 94 | }
|
77 | 95 | }
|
78 | 96 |
|
79 | 97 | // property promotion
|
80 | 98 | // has `#[AllowDynamicProperties]`
|
81 | 99 |
|
82 |
| - return $node; |
| 100 | + return false; |
83 | 101 | }
|
84 | 102 |
|
85 | 103 | public function provideMinPhpVersion(): int
|
|
0 commit comments