forked from phpstan/phpstan-src
/
ReadOnlyPropertyAssignRule.php
84 lines (68 loc) · 2.65 KB
/
ReadOnlyPropertyAssignRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Properties;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\PropertyAssignNode;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ThisType;
use function sprintf;
use function strtolower;
/**
* @implements Rule<PropertyAssignNode>
*/
class ReadOnlyPropertyAssignRule implements Rule
{
public function __construct(private PropertyReflectionFinder $propertyReflectionFinder)
{
}
public function getNodeType(): string
{
return PropertyAssignNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$propertyFetch = $node->getPropertyFetch();
if (!$propertyFetch instanceof Node\Expr\PropertyFetch) {
return [];
}
$errors = [];
$reflections = $this->propertyReflectionFinder->findPropertyReflectionsFromNode($propertyFetch, $scope);
foreach ($reflections as $propertyReflection) {
$nativeReflection = $propertyReflection->getNativeReflection();
if ($nativeReflection === null) {
continue;
}
if (!$scope->canAccessProperty($propertyReflection)) {
continue;
}
if (!$nativeReflection->isReadOnly()) {
continue;
}
$declaringClass = $nativeReflection->getDeclaringClass();
if (!$scope->isInClass()) {
$errors[] = RuleErrorBuilder::message(sprintf('Readonly property %s::$%s is assigned outside of its declaring class.', $declaringClass->getDisplayName(), $propertyReflection->getName()))->build();
continue;
}
$scopeClassReflection = $scope->getClassReflection();
if ($scopeClassReflection->getName() !== $declaringClass->getName()) {
$errors[] = RuleErrorBuilder::message(sprintf('Readonly property %s::$%s is assigned outside of its declaring class.', $declaringClass->getDisplayName(), $propertyReflection->getName()))->build();
continue;
}
$scopeMethod = $scope->getFunction();
if (!$scopeMethod instanceof MethodReflection) {
throw new ShouldNotHappenException();
}
if (strtolower($scopeMethod->getName()) === '__construct' || strtolower($scopeMethod->getName()) === '__unserialize') {
if (!$scope->getType($propertyFetch->var) instanceof ThisType) {
$errors[] = RuleErrorBuilder::message(sprintf('Readonly property %s::$%s is not assigned on $this.', $declaringClass->getDisplayName(), $propertyReflection->getName()))->build();
}
continue;
}
$errors[] = RuleErrorBuilder::message(sprintf('Readonly property %s::$%s is assigned outside of the constructor.', $declaringClass->getDisplayName(), $propertyReflection->getName()))->build();
}
return $errors;
}
}