Skip to content

Commit 91551de

Browse files
committed
Prevent "Unsafe usage of new static() in abstract class" with final constructor
1 parent 8bb2a20 commit 91551de

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Rules/Classes/NewStaticInAbstractClassStaticMethodRule.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PhpParser\Node;
66
use PHPStan\Analyser\Scope;
77
use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
8+
use PHPStan\Reflection\Php\PhpMethodReflection;
89
use PHPStan\Rules\Rule;
910
use PHPStan\Rules\RuleErrorBuilder;
1011
use function sprintf;
@@ -49,6 +50,15 @@ public function processNode(Node $node, Scope $scope): array
4950
return [];
5051
}
5152

53+
if ($classReflection->hasConstructor()) {
54+
$constructor = $classReflection->getConstructor();
55+
if (
56+
$constructor->isFinal()->yes()
57+
) {
58+
return [];
59+
}
60+
}
61+
5262
return [
5363
RuleErrorBuilder::message(sprintf(
5464
'Unsafe usage of new static() in abstract class %s in static method %s().',

tests/PHPStan/Rules/Classes/data/new-static-in-abstract-class-static-method.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,23 @@ public static function staticDoFoo(): void
3131
}
3232

3333
}
34+
35+
abstract class FinalConstructFoo
36+
{
37+
final function __construct() {
38+
39+
}
40+
41+
public function doFoo(): void
42+
{
43+
new static();
44+
}
45+
46+
public static function staticDoFoo(): void
47+
{
48+
new static();
49+
}
50+
51+
}
52+
53+
class Subclass extends FinalConstructFoo {}

0 commit comments

Comments
 (0)