forked from symplify/phpstan-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForbiddenClassConstRule.php
111 lines (95 loc) · 2.62 KB
/
ForbiddenClassConstRule.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
declare(strict_types=1);
namespace Symplify\PHPStanRules\Rules\Enum;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassNode;
use PHPStan\Reflection\ClassReflection;
use Symplify\PHPStanRules\Rules\AbstractSymplifyRule;
use Symplify\RuleDocGenerator\Contract\ConfigurableRuleInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Symplify\PHPStanRules\Tests\Rules\Enum\ForbiddenClassConstRule\ForbiddenClassConstRuleTest
*/
final class ForbiddenClassConstRule extends AbstractSymplifyRule implements ConfigurableRuleInterface
{
/**
* @var string
*/
public const ERROR_MESSAGE = 'Constants in this class are not allowed, move them to custom Enum class instead';
/**
* @param array<class-string> $classTypes
*/
public function __construct(
private array $classTypes
) {
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [InClassNode::class];
}
/**
* @param InClassNode $node
* @return string[]
*/
public function process(Node $node, Scope $scope): array
{
$classLike = $node->getOriginalNode();
if ($classLike->getConstants() === []) {
return [];
}
if (! $this->isInClassTypes($scope, $this->classTypes)) {
return [];
}
return [self::ERROR_MESSAGE];
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(self::ERROR_MESSAGE, [
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
final class Product extends AbstractEntity
{
public const TYPE_HIDDEN = 0;
public const TYPE_VISIBLE = 1;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class Product extends AbstractEntity
{
}
class ProductVisibility extends Enum
{
public const HIDDEN = 0;
public const VISIBLE = 1;
}
CODE_SAMPLE
,
[
'classTypes' => ['AbstractEntity'],
]
),
]);
}
/**
* @param class-string[] $classTypes
*/
private function isInClassTypes(Scope $scope, array $classTypes): bool
{
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
foreach ($classTypes as $classType) {
if ($classReflection->isSubclassOf($classType)) {
return true;
}
}
return false;
}
}