Skip to content

Commit d631120

Browse files
committed
Internal PHPStan rule - class must be abstract or final
1 parent 5baa146 commit d631120

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Build;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\Node\InClassNode;
8+
use PHPStan\Reflection\FunctionVariant;
9+
use PHPStan\Reflection\FunctionVariantWithPhpDocs;
10+
use PHPStan\Reflection\Php\DummyParameter;
11+
use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
12+
use PHPStan\Rules\Rule;
13+
use PHPStan\Rules\RuleErrorBuilder;
14+
use PHPStan\Type\Type;
15+
use function in_array;
16+
use function sprintf;
17+
18+
/**
19+
* @implements Rule<InClassNode>
20+
*/
21+
final class FinalClassRule implements Rule
22+
{
23+
24+
public function getNodeType(): string
25+
{
26+
return InClassNode::class;
27+
}
28+
29+
public function processNode(Node $node, Scope $scope): array
30+
{
31+
$classReflection = $node->getClassReflection();
32+
if (!$classReflection->isClass()) {
33+
return [];
34+
}
35+
if ($classReflection->isAbstract()) {
36+
return [];
37+
}
38+
if ($classReflection->isFinal()) {
39+
return [];
40+
}
41+
if ($classReflection->isSubclassOf(Type::class)) {
42+
return [];
43+
}
44+
45+
// exceptions
46+
if (in_array($classReflection->getName(), [
47+
FunctionVariant::class,
48+
FunctionVariantWithPhpDocs::class,
49+
DummyParameter::class,
50+
PhpFunctionFromParserNodeReflection::class,
51+
], true)) {
52+
return [];
53+
}
54+
55+
return [
56+
RuleErrorBuilder::message(
57+
sprintf('Class %s must be abstract or final.', $classReflection->getDisplayName()),
58+
)
59+
->identifier('phpstan.finalClass')
60+
->build(),
61+
];
62+
}
63+
64+
}

build/phpstan.neon

+4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ includes:
99
- ../phpstan-baseline.php
1010
- ignore-by-php-version.neon.php
1111
- ignore-by-architecture.neon.php
12+
1213
parameters:
1314
level: 8
1415
paths:
@@ -98,6 +99,9 @@ parameters:
9899
- stubs/NetteDIContainer.stub
99100
- stubs/PhpParserName.stub
100101

102+
rules:
103+
- PHPStan\Build\FinalClassRule
104+
101105
services:
102106
-
103107
class: PHPStan\Build\ServiceLocatorDynamicReturnTypeExtension

0 commit comments

Comments
 (0)