Skip to content

Commit 54f3522

Browse files
phpstan-botondrejmirtes
authored andcommitted
Report error when trying to instantiate a trait with new
- Added trait check to InstantiationRule alongside existing checks for enums, interfaces, and abstract classes - New error message: "Cannot instantiate trait X." with identifier "new.trait" - New regression test in tests/PHPStan/Rules/Classes/data/bug-14251.php Closes phpstan/phpstan#14251
1 parent 38cdabb commit 54f3522

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

src/Rules/Classes/InstantiationRule.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,14 @@ private function checkClassName(string $class, bool $isName, Node $node, Scope $
156156
$classReflection = $this->reflectionProvider->getClass($class);
157157
}
158158

159+
if ($classReflection->isTrait() && $isName) {
160+
return [
161+
RuleErrorBuilder::message(
162+
sprintf('Cannot instantiate trait %s.', $classReflection->getDisplayName()),
163+
)->identifier('new.trait')->build(),
164+
];
165+
}
166+
159167
if ($classReflection->isEnum() && $isName) {
160168
return [
161169
RuleErrorBuilder::message(

tests/PHPStan/Rules/Classes/InstantiationRuleTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,4 +599,14 @@ public function testNewStaticWithConsistentConstructor(): void
599599
]);
600600
}
601601

602+
public function testBug14251(): void
603+
{
604+
$this->analyse([__DIR__ . '/data/bug-14251.php'], [
605+
[
606+
'Cannot instantiate trait Bug14251\InternalTrait.',
607+
9,
608+
],
609+
]);
610+
}
611+
602612
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug14251;
4+
5+
trait InternalTrait {
6+
public function doSomething(): void {}
7+
}
8+
9+
$obj = new InternalTrait();

0 commit comments

Comments
 (0)