Skip to content

Commit fa467b1

Browse files
committed
Prevent declaring hooked properties as readonly
1 parent 0b28f60 commit fa467b1

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

src/Rules/Properties/PropertyInClassRule.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@ public function processNode(Node $node, Scope $scope): array
7676
return [];
7777
}
7878

79+
if ($node->isReadOnly()) {
80+
return [
81+
RuleErrorBuilder::message('Hooked properties cannot be readonly.')
82+
->nonIgnorable()
83+
->identifier('property.hookReadOnly')
84+
->build(),
85+
];
86+
}
87+
7988
if (!$this->doAllHooksHaveBody($node)) {
8089
return [
8190
RuleErrorBuilder::message('Non-abstract properties cannot include hooks without bodies.')

tests/PHPStan/Rules/Properties/PropertyInClassRuleTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,26 @@ public function testPhp84AndAbstractHookedPropertiesWithBodies(): void
151151
]);
152152
}
153153

154+
public function testPhp84AndReadonlyHookedProperties(): void
155+
{
156+
if (PHP_VERSION_ID < 80400) {
157+
$this->markTestSkipped('Test requires PHP 8.4 or later.');
158+
}
159+
160+
$this->analyse([__DIR__ . '/data/readonly-property-hooks.php'], [
161+
[
162+
'Hooked properties cannot be readonly.',
163+
7,
164+
],
165+
[
166+
'Hooked properties cannot be readonly.',
167+
12,
168+
],
169+
[
170+
'Hooked properties cannot be readonly.',
171+
14,
172+
]
173+
]);
174+
}
175+
154176
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace ReadonlyPropertyHooks;
4+
5+
class HelloWorld
6+
{
7+
public readonly $firstName {
8+
get => $this->firstName;
9+
set => $this->firstName;
10+
}
11+
12+
public readonly $middleName { get => $this->middleName; }
13+
14+
public readonly $lastName { set => $this->lastName; }
15+
}

0 commit comments

Comments
 (0)