Skip to content

Commit 0999d0f

Browse files
committed
fix class fake
1 parent 0b750a9 commit 0999d0f

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/Rules/Traits/TraitAttributesRule.php

+7-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Attribute;
66
use PhpParser\Node;
7+
use PhpParser\Node\Stmt\Class_;
78
use PHPStan\Analyser\MutatingScope;
89
use PHPStan\Analyser\Scope;
910
use PHPStan\Reflection\ReflectionProvider;
@@ -41,12 +42,15 @@ public function processNode(Node $node, Scope $scope): array
4142
if (!$this->reflectionProvider->hasClass($traitName->toString())) {
4243
return [];
4344
}
44-
$classReflection = $this->reflectionProvider->getClass($traitName->toString());
45+
$traitClassReflection = $this->reflectionProvider->getClass($traitName->toString());
4546

4647
if (!$scope instanceof MutatingScope) {
4748
throw new ShouldNotHappenException();
4849
}
49-
$scope = $scope->enterTrait($classReflection);
50+
$fakeClass = new Class_(null, ['stmts' => [new Node\Stmt\TraitUse([$traitName])]], ['startLine' => 1, 'endLine' => 1]);
51+
$fakeClassReflection = $this->reflectionProvider->getAnonymousClassReflection($fakeClass, $scope);
52+
$scope = $scope->enterClass($fakeClassReflection);
53+
$scope = $scope->enterTrait($traitClassReflection);
5054

5155
$errors = $this->attributesCheck->check(
5256
$scope,
@@ -55,7 +59,7 @@ public function processNode(Node $node, Scope $scope): array
5559
'class',
5660
);
5761

58-
if (count($classReflection->getNativeReflection()->getAttributes('AllowDynamicProperties')) > 0) {
62+
if (count($traitClassReflection->getNativeReflection()->getAttributes('AllowDynamicProperties')) > 0) {
5963
$errors[] = RuleErrorBuilder::message('Attribute class AllowDynamicProperties cannot be used with trait.')
6064
->identifier('trait.allowDynamicProperties')
6165
->nonIgnorable()

tests/PHPStan/Rules/Traits/data/bug-12011.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,23 @@
88
#[Table(self::TABLE_NAME)]
99
trait MyTrait
1010
{
11-
private const int TABLE_NAME = 'table';
11+
private const int TABLE_NAME = 1;
1212
}
1313

1414
class X {
1515
use MyTrait;
1616
}
1717

18+
#[Table(self::TABLE_NAME)]
19+
trait MyTrait2
20+
{
21+
private const string TABLE_NAME = 'table';
22+
}
23+
24+
class Y {
25+
use MyTrait2;
26+
}
27+
1828
#[Attribute(Attribute::TARGET_CLASS)]
1929
final class Table
2030
{

0 commit comments

Comments
 (0)