forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethodSignatureRule.php
More file actions
251 lines (230 loc) · 8.91 KB
/
Copy pathMethodSignatureRule.php
File metadata and controls
251 lines (230 loc) · 8.91 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Methods;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ExtendedParameterReflection;
use PHPStan\Reflection\ExtendedParametersAcceptor;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StaticType;
use PHPStan\Type\Type;
use PHPStan\Type\TypehintHelper;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\VerbosityLevel;
use function count;
use function min;
use function sprintf;
use function strtolower;
/**
* @implements Rule<InClassMethodNode>
*/
final class MethodSignatureRule implements Rule
{
public function __construct(
private ParentMethodHelper $parentMethodHelper,
private bool $reportMaybes,
private bool $reportStatic,
private bool $reportMethodPurityOverride,
)
{
}
public function getNodeType(): string
{
return InClassMethodNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$method = $node->getMethodReflection();
$methodName = $method->getName();
if ($methodName === '__construct') {
return [];
}
if (!$this->reportStatic && $method->isStatic()) {
return [];
}
if ($method->isPrivate()) {
return [];
}
$errors = [];
$declaringClass = $method->getDeclaringClass();
foreach ($this->parentMethodHelper->collectParentMethods($methodName, $method->getDeclaringClass()) as [$parentMethod, $parentMethodDeclaringClass]) {
if ($this->reportMethodPurityOverride && $method->isPure()->no() && $parentMethod->isPure()->yes()) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Impure method %s::%s() overrides pure method %s::%s().',
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$parentMethodDeclaringClass->getDisplayName(),
$parentMethod->getName(),
))->identifier('method.impure')->build();
}
$parentVariants = $parentMethod->getVariants();
if (count($parentVariants) !== 1) {
continue;
}
$parentVariant = $parentVariants[0];
[$returnTypeCompatibility, $returnType, $parentReturnType] = $this->checkReturnTypeCompatibility($declaringClass, $method, $parentVariant);
if ($returnTypeCompatibility->no() || (!$returnTypeCompatibility->yes() && $this->reportMaybes)) {
$builder = RuleErrorBuilder::message(sprintf(
'Return type (%s) of method %s::%s() should be %s with return type (%s) of method %s::%s()',
$returnType->describe(VerbosityLevel::value()),
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$returnTypeCompatibility->no() ? 'compatible' : 'covariant',
$parentReturnType->describe(VerbosityLevel::value()),
$parentMethodDeclaringClass->getDisplayName(),
$parentMethod->getName(),
))->identifier('method.childReturnType');
if (
$parentMethod->getDeclaringClass()->getName() === Rule::class
&& strtolower($methodName) === 'processnode'
) {
$ruleErrorType = new ObjectType(RuleError::class);
$identifierRuleErrorType = new ObjectType(IdentifierRuleError::class);
$listOfIdentifierRuleErrors = new IntersectionType([
new ArrayType(IntegerRangeType::fromInterval(0, null), $identifierRuleErrorType),
new AccessoryArrayListType(),
]);
if ($listOfIdentifierRuleErrors->isSuperTypeOf($parentReturnType)->yes()) {
$returnValueType = $returnType->getIterableValueType();
if (!$returnValueType->isString()->no()) {
$builder->tip('Rules can no longer return plain strings. See: https://phpstan.org/blog/using-rule-error-builder');
} elseif (
$ruleErrorType->isSuperTypeOf($returnValueType)->yes()
&& !$identifierRuleErrorType->isSuperTypeOf($returnValueType)->yes()
) {
$builder->tip('Errors are missing identifiers. See: https://phpstan.org/blog/using-rule-error-builder');
} elseif (!$returnType->isList()->yes()) {
$builder->tip('Return type must be a list. See: https://phpstan.org/blog/using-rule-error-builder');
}
}
}
$errors[] = $builder->build();
}
$methodParameters = $method->getParameters();
$parentVariantParameters = $parentVariant->getParameters();
$parameterResults = $this->checkParameterTypeCompatibility($declaringClass, $methodParameters, $parentVariantParameters);
foreach ($parameterResults as $parameterIndex => [$parameterResult, $parameterType, $parentParameterType]) {
if ($parameterResult->yes()) {
continue;
}
if (!$parameterResult->no() && !$this->reportMaybes) {
continue;
}
$parameter = $methodParameters[$parameterIndex];
$parentParameter = $parentVariantParameters[$parameterIndex];
$errors[] = RuleErrorBuilder::message(sprintf(
'Parameter #%d $%s (%s) of method %s::%s() should be %s with parameter $%s (%s) of method %s::%s()',
$parameterIndex + 1,
$parameter->getName(),
$parameterType->describe(VerbosityLevel::value()),
$method->getDeclaringClass()->getDisplayName(),
$method->getName(),
$parameterResult->no() ? 'compatible' : 'contravariant',
$parentParameter->getName(),
$parentParameterType->describe(VerbosityLevel::value()),
$parentMethodDeclaringClass->getDisplayName(),
$parentMethod->getName(),
))->identifier('method.childParameterType')->build();
}
}
return $errors;
}
/**
* @return array{TrinaryLogic, Type, Type}
*/
private function checkReturnTypeCompatibility(
ClassReflection $declaringClass,
ExtendedParametersAcceptor $currentVariant,
ExtendedParametersAcceptor $parentVariant,
): array
{
$returnType = TypehintHelper::decideType(
$currentVariant->getNativeReturnType(),
TemplateTypeHelper::resolveToBounds($currentVariant->getPhpDocReturnType()),
);
$originalParentReturnType = TypehintHelper::decideType(
$parentVariant->getNativeReturnType(),
TemplateTypeHelper::resolveToBounds($parentVariant->getPhpDocReturnType()),
);
$parentReturnType = $this->transformStaticType($declaringClass, $originalParentReturnType);
// Allow adding `void` return type hints when the parent defines no return type
if ($returnType->isVoid()->yes() && $parentReturnType instanceof MixedType) {
return [TrinaryLogic::createYes(), $returnType, $parentReturnType];
}
// We can return anything
if ($parentReturnType->isVoid()->yes()) {
return [TrinaryLogic::createYes(), $returnType, $parentReturnType];
}
return [$parentReturnType->isSuperTypeOf($returnType)->result, TypehintHelper::decideType(
$currentVariant->getNativeReturnType(),
$currentVariant->getPhpDocReturnType(),
), $originalParentReturnType];
}
/**
* @param ExtendedParameterReflection[] $parameters
* @param ExtendedParameterReflection[] $parentParameters
* @return array<int, array{TrinaryLogic, Type, Type}>
*/
private function checkParameterTypeCompatibility(
ClassReflection $declaringClass,
array $parameters,
array $parentParameters,
): array
{
$parameterResults = [];
$numberOfParameters = min(count($parameters), count($parentParameters));
for ($i = 0; $i < $numberOfParameters; $i++) {
$parameter = $parameters[$i];
$parentParameter = $parentParameters[$i];
$parameterType = TypehintHelper::decideType(
$parameter->getNativeType(),
TemplateTypeHelper::resolveToBounds($parameter->getPhpDocType()),
);
$originalParameterType = TypehintHelper::decideType(
$parentParameter->getNativeType(),
TemplateTypeHelper::resolveToBounds($parentParameter->getPhpDocType()),
);
$parentParameterType = $this->transformStaticType($declaringClass, $originalParameterType);
$parameterResults[] = [$parameterType->isSuperTypeOf($parentParameterType)->result, TypehintHelper::decideType(
$parameter->getNativeType(),
$parameter->getPhpDocType(),
), $originalParameterType];
}
return $parameterResults;
}
private function transformStaticType(ClassReflection $declaringClass, Type $type): Type
{
return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($declaringClass): Type {
if ($type instanceof GenericStaticType) {
if ($declaringClass->isFinal()) {
$changedType = $type->changeBaseClass($declaringClass)->getStaticObjectType();
} else {
$changedType = $type->changeBaseClass($declaringClass);
}
return $traverse($changedType);
}
if ($type instanceof StaticType) {
if ($declaringClass->isFinal()) {
$changedType = new ObjectType($declaringClass->getName());
} else {
$changedType = $type->changeBaseClass($declaringClass);
}
return $traverse($changedType);
}
return $traverse($type);
});
}
}