Skip to content

Commit

Permalink
Readonly classes cannot be combined with #[AllowDynamicProperties]
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Dec 17, 2024
1 parent c053dbc commit 60a28e2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Rules/Classes/ClassAttributesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
use PHPStan\Node\InClassNode;
use PHPStan\Rules\AttributesCheck;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function count;
use function sprintf;

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

return $this->attributesCheck->check(
$errors = $this->attributesCheck->check(
$scope,
$classLikeNode->attrGroups,
Attribute::TARGET_CLASS,
'class',
);

$classReflection = $scope->getClassReflection();
if ($classReflection !== null && $classReflection->isReadOnly()) {
if (count($classReflection->getNativeReflection()->getAttributes('AllowDynamicProperties')) > 0) {
$errors[] = RuleErrorBuilder::message(sprintf('Cannot apply #[AllowDynamicProperties] to readonly class %s.', $classReflection->getName()))
->identifier('class.allowDynamicPropertiesReadonly')
->build();
}
}

return $errors;
}

}
16 changes: 16 additions & 0 deletions tests/PHPStan/Rules/Classes/ClassAttributesRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,20 @@ public function testBug12011(): void
]);
}

public function testBug12281(): void
{
if (PHP_VERSION_ID < 80200) {
$this->markTestSkipped('Test requires PHP 8.2.');
}

$this->checkExplicitMixed = true;
$this->checkImplicitMixed = true;
$this->analyse([__DIR__ . '/data/bug-12281.php'], [
[
'Cannot apply #[AllowDynamicProperties] to readonly class Bug12281\BlogData.',
05,
],
]);
}

}
6 changes: 6 additions & 0 deletions tests/PHPStan/Rules/Classes/data/bug-12281.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php // lint >= 8.2

namespace Bug12281;

#[\AllowDynamicProperties]
readonly class BlogData { /* … */ }

0 comments on commit 60a28e2

Please sign in to comment.