-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMissingDefaultValueForTypedPropertyRule.php
101 lines (83 loc) · 2.64 KB
/
MissingDefaultValueForTypedPropertyRule.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
<?php
declare(strict_types=1);
namespace Ssch\Typo3PhpstanRules\Rules;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Property;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use Ssch\Typo3PhpstanRules\NodeAnalyzer\Extbase\EntityClassDetector;
use Symplify\RuleDocGenerator\Contract\DocumentedRuleInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @implements Rule<Class_>
*/
final class MissingDefaultValueForTypedPropertyRule implements Rule, DocumentedRuleInterface
{
/**
* @var string
*/
public const ERROR_MESSAGE = 'Missing default value for property "%s" in class "%s"';
private EntityClassDetector $entityClassDetector;
public function __construct(EntityClassDetector $entityClassDetector)
{
$this->entityClassDetector = $entityClassDetector;
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Missing default value for property "property" in class "MissingDefaultValueForTypedProperty"',
[
new CodeSample(
<<<'CODE_SAMPLE'
final class MissingDefaultValueForTypedProperty extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
protected string $property;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class MissingDefaultValueForTypedProperty extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
protected string $property = '';
}
CODE_SAMPLE
),
]
);
}
public function getNodeType(): string
{
return Class_::class;
}
/**
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (! $this->entityClassDetector->isInsideExtbaseEntity($node)) {
return [];
}
foreach ($node->getProperties() as $property) {
if ($this->shouldSkipProperty($property)) {
continue;
}
return [$this->createErrorMessage($property, $node->namespacedName->toString())];
}
return [];
}
private function createErrorMessage(Property $node, string $className): string
{
$propertyProperty = $node->props[0];
return sprintf(self::ERROR_MESSAGE, $propertyProperty->name, $className);
}
private function shouldSkipProperty(Property $property): bool
{
if ($property->type === null) {
return true;
}
$propertyProperty = $property->props[0];
return $propertyProperty->default !== null;
}
}