-
Notifications
You must be signed in to change notification settings - Fork 571
Expand file tree
/
Copy pathFinalClassRule.php
More file actions
88 lines (75 loc) · 2.14 KB
/
FinalClassRule.php
File metadata and controls
88 lines (75 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php declare(strict_types = 1);
namespace PHPStan\Build;
use PhpParser\Modifiers;
use PhpParser\Node;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\File\FileHelper;
use PHPStan\Node\InClassNode;
use PHPStan\Reflection\FunctionVariant;
use PHPStan\Reflection\ExtendedFunctionVariant;
use PHPStan\Reflection\Php\DummyParameter;
use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Type;
use function in_array;
use function sprintf;
use function str_starts_with;
/**
* @implements Rule<InClassNode>
*/
final class FinalClassRule implements Rule
{
public function __construct(private FileHelper $fileHelper, private bool $skipTests = true)
{
}
public function getNodeType(): string
{
return InClassNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$classReflection = $node->getClassReflection();
if (!$classReflection->isClass()) {
return [];
}
if ($classReflection->isAbstract()) {
return [];
}
if ($classReflection->isFinal()) {
return [];
}
if ($classReflection->is(Type::class)) {
return [];
}
// exceptions
if (in_array($classReflection->getName(), [
FunctionVariant::class,
ExtendedFunctionVariant::class,
DummyParameter::class,
PhpFunctionFromParserNodeReflection::class,
NodeScopeResolver::class,
MutatingScope::class,
], true)) {
return [];
}
if ($this->skipTests && str_starts_with($this->fileHelper->normalizePath($scope->getFile()), $this->fileHelper->normalizePath(dirname(__DIR__, 3) . '/tests'))) {
return [];
}
$errorBuilder = RuleErrorBuilder::message(
sprintf('Class %s must be abstract or final.', $classReflection->getDisplayName()),
)->identifier('phpstan.finalClass');
$originalNode = $node->getOriginalNode();
if ($originalNode instanceof Node\Stmt\Class_ && $originalNode->name !== null) {
$errorBuilder->fixNode($originalNode, static function ($classNode) {
$classNode->flags |= Modifiers::FINAL;
return $classNode;
});
}
return [
$errorBuilder->build(),
];
}
}