Skip to content

Commit 60a28e2

Browse files
committed
Readonly classes cannot be combined with #[AllowDynamicProperties]
1 parent c053dbc commit 60a28e2

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

src/Rules/Classes/ClassAttributesRule.php

+15-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
use PHPStan\Node\InClassNode;
99
use PHPStan\Rules\AttributesCheck;
1010
use PHPStan\Rules\Rule;
11+
use PHPStan\Rules\RuleErrorBuilder;
12+
use function count;
13+
use function sprintf;
1114

1215
/**
1316
* @implements Rule<InClassNode>
@@ -28,12 +31,23 @@ public function processNode(Node $node, Scope $scope): array
2831
{
2932
$classLikeNode = $node->getOriginalNode();
3033

31-
return $this->attributesCheck->check(
34+
$errors = $this->attributesCheck->check(
3235
$scope,
3336
$classLikeNode->attrGroups,
3437
Attribute::TARGET_CLASS,
3538
'class',
3639
);
40+
41+
$classReflection = $scope->getClassReflection();
42+
if ($classReflection !== null && $classReflection->isReadOnly()) {
43+
if (count($classReflection->getNativeReflection()->getAttributes('AllowDynamicProperties')) > 0) {
44+
$errors[] = RuleErrorBuilder::message(sprintf('Cannot apply #[AllowDynamicProperties] to readonly class %s.', $classReflection->getName()))
45+
->identifier('class.allowDynamicPropertiesReadonly')
46+
->build();
47+
}
48+
}
49+
50+
return $errors;
3751
}
3852

3953
}

tests/PHPStan/Rules/Classes/ClassAttributesRuleTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -168,4 +168,20 @@ public function testBug12011(): void
168168
]);
169169
}
170170

171+
public function testBug12281(): void
172+
{
173+
if (PHP_VERSION_ID < 80200) {
174+
$this->markTestSkipped('Test requires PHP 8.2.');
175+
}
176+
177+
$this->checkExplicitMixed = true;
178+
$this->checkImplicitMixed = true;
179+
$this->analyse([__DIR__ . '/data/bug-12281.php'], [
180+
[
181+
'Cannot apply #[AllowDynamicProperties] to readonly class Bug12281\BlogData.',
182+
05,
183+
],
184+
]);
185+
}
186+
171187
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php // lint >= 8.2
2+
3+
namespace Bug12281;
4+
5+
#[\AllowDynamicProperties]
6+
readonly class BlogData { /* … */ }

0 commit comments

Comments
 (0)