Skip to content

Commit d56d084

Browse files
committed
Class constants cannot be directly accessed on a trait
1 parent 1475859 commit d56d084

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed

src/Rules/Classes/ClassConstantRule.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,24 @@ public function processNode(Node $node, Scope $scope): array
111111
];
112112
}
113113

114-
$messages = $this->classCheck->checkClassNames([new ClassNameNodePair($className, $class)]);
115-
116114
$classType = $scope->resolveTypeByName($class);
115+
if (strtolower($constantName) !== 'class') {
116+
foreach ($classType->getObjectClassReflections() as $classTypeReflection) {
117+
if (!$classTypeReflection->isTrait()) {
118+
continue;
119+
}
120+
121+
return [
122+
RuleErrorBuilder::message(sprintf(
123+
'Cannot access constant %s on trait %s.',
124+
$constantName,
125+
$classTypeReflection->getDisplayName(),
126+
))->identifier('classConstant.onTrait')->build(),
127+
];
128+
}
129+
}
130+
131+
$messages = $this->classCheck->checkClassNames([new ClassNameNodePair($className, $class)]);
117132
}
118133

119134
if (strtolower($constantName) === 'class') {

tests/PHPStan/Rules/Classes/ClassConstantRuleTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,4 +420,19 @@ public function testPhpstanInternalClass(): void
420420
]);
421421
}
422422

423+
public function testClassConstantAccessedOnTrait(): void
424+
{
425+
if (PHP_VERSION_ID < 80200) {
426+
$this->markTestSkipped('Test requires PHP 8.2.');
427+
}
428+
429+
$this->phpVersion = PHP_VERSION_ID;
430+
$this->analyse([__DIR__ . '/data/class-constant-accessed-on-trait.php'], [
431+
[
432+
'Cannot access constant TEST on trait ClassConstantAccessedOnTrait\Foo.',
433+
16,
434+
],
435+
]);
436+
}
437+
423438
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php // lint >= 8.2
2+
3+
namespace ClassConstantAccessedOnTrait;
4+
5+
trait Foo
6+
{
7+
public const TEST = 1;
8+
}
9+
10+
class Bar
11+
{
12+
use Foo;
13+
}
14+
15+
function (): void {
16+
echo Foo::TEST;
17+
echo Foo::class;
18+
};

0 commit comments

Comments
 (0)