-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDoNotUseNullableConstructorRule.php
99 lines (82 loc) · 2.5 KB
/
DoNotUseNullableConstructorRule.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
<?php
declare(strict_types=1);
namespace Ssch\Typo3PhpstanRules\Rules;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\UnionType;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Symplify\PackageBuilder\ValueObject\MethodName;
use Symplify\RuleDocGenerator\Contract\DocumentedRuleInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @implements Rule<ClassMethod>
*/
final class DoNotUseNullableConstructorRule implements Rule, DocumentedRuleInterface
{
/**
* @var string
*/
public const MESSAGE = 'Do not use nullable argument in constructor. Use Symfony Dependency Injection';
public function getNodeType(): string
{
return ClassMethod::class;
}
/**
* @param ClassMethod $node
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->name->toString() !== MethodName::CONSTRUCTOR) {
return [];
}
foreach ($node->params as $param) {
if ($this->shouldSkipParam($param)) {
continue;
}
return [self::MESSAGE];
}
return [];
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Do not use nullable constructor arguments for classes. Use Symfony Dependency Injection Configuration properly.',
[
new CodeSample(
<<<'CODE_SAMPLE'
public function __construct(?MyService $myService = null)
CODE_SAMPLE
,
'public function __construct(MyService $myService)'
),
]
);
}
private function shouldSkipParam(Param $param): bool
{
if ($param->default === null) {
return true;
}
if ($param->type instanceof NullableType && $param->type->type instanceof FullyQualified) {
return false;
}
if ($param->type instanceof UnionType) {
foreach ($param->type->types as $type) {
if (! $type instanceof Identifier) {
continue;
}
if ($type->name !== 'null') {
continue;
}
return false;
}
}
return true;
}
}