Skip to content

Commit 4d7274d

Browse files
committed
fix class fake
1 parent 0b750a9 commit 4d7274d

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

Diff for: src/Rules/Traits/TraitAttributesRule.php

+12-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;
@@ -19,6 +20,8 @@
1920
final class TraitAttributesRule implements Rule
2021
{
2122

23+
private int $classId = 1;
24+
2225
public function __construct(
2326
private AttributesCheck $attributesCheck,
2427
private ReflectionProvider $reflectionProvider,
@@ -41,12 +44,18 @@ public function processNode(Node $node, Scope $scope): array
4144
if (!$this->reflectionProvider->hasClass($traitName->toString())) {
4245
return [];
4346
}
44-
$classReflection = $this->reflectionProvider->getClass($traitName->toString());
47+
$traitClassReflection = $this->reflectionProvider->getClass($traitName->toString());
4548

4649
if (!$scope instanceof MutatingScope) {
4750
throw new ShouldNotHappenException();
4851
}
49-
$scope = $scope->enterTrait($classReflection);
52+
53+
$fakeClass = new Class_(null, ['stmts' => [new Node\Stmt\TraitUse([$traitName])]], ['startLine' => $this->classId, 'endLine' => $this->classId]);
54+
$this->classId++;
55+
56+
$fakeClassReflection = $this->reflectionProvider->getAnonymousClassReflection($fakeClass, $scope);
57+
$scope = $scope->enterClass($fakeClassReflection);
58+
$scope = $scope->enterTrait($traitClassReflection);
5059

5160
$errors = $this->attributesCheck->check(
5261
$scope,
@@ -55,7 +64,7 @@ public function processNode(Node $node, Scope $scope): array
5564
'class',
5665
);
5766

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

Diff for: 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)