Repository navigation
Expand file tree
/
Copy pathIssetCheck.php
More file actions
329 lines (280 loc) · 10.1 KB
/
Copy pathIssetCheck.php
File metadata and controls
329 lines (280 loc) · 10.1 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<?php declare(strict_types = 1);
namespace PHPStan\Rules;
use PhpParser\Node\Expr\NullsafePropertyFetch;
use PhpParser\Node\Identifier;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\IssetabilityResolution;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Rules\Properties\PropertyDescriptor;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
use function str_starts_with;
/**
* Renders the isset/empty/?? "does it make sense" errors from the single
* IssetabilityResolution the engine already computed. The chain is walked and
* resolved once (IssetabilityDescriptor::resolve); this only projects the
* resolved facts into messages - it never re-walks the AST nor re-resolves types.
*
* @phpstan-type ErrorIdentifier = 'empty'|'isset'|'nullCoalesce'
*/
#[AutowiredService]
final class IssetCheck
{
public function __construct(
private PropertyDescriptor $propertyDescriptor,
#[AutowiredParameter]
private bool $checkAdvancedIsset,
#[AutowiredParameter]
private bool $treatPhpDocTypesAsCertain,
)
{
}
/**
* @param ErrorIdentifier $identifier
* @param callable(Type): ?string $typeMessageCallback
* @param int|null $line null reports the error on the line of the node the error is attached to
*/
public function check(ExpressionResult $exprResult, Scope $scope, string $operatorDescription, string $identifier, callable $typeMessageCallback, ?int $line = null): ?IdentifierRuleError
{
$walkScope = $scope->toWalkScope();
$resolution = $exprResult->getIssetabilityResolution($walkScope, !$this->treatPhpDocTypesAsCertain, true);
return $this->doCheck($resolution, $walkScope, $operatorDescription, $identifier, $typeMessageCallback, null, $line);
}
/**
* @param ErrorIdentifier $identifier
* @param callable(Type): ?string $typeMessageCallback
*/
private function doCheck(IssetabilityResolution $resolution, MutatingScope $scope, string $operatorDescription, string $identifier, callable $typeMessageCallback, ?IdentifierRuleError $error, ?int $line): ?IdentifierRuleError
{
$link = $resolution->getLink();
$inner = $resolution->getInner();
if ($link->isVariable()) {
$hasVariable = $link->getHasVariable();
if ($hasVariable->maybe()) {
return null;
}
if ($error === null) {
if ($hasVariable->yes()) {
if ($link->getVariableName() === '_SESSION') {
return null;
}
$type = $link->getValueType();
if (!$type instanceof NeverType) {
return $this->generateError(
$type,
sprintf('Variable $%s %s always exists and', $link->getVariableName(), $operatorDescription),
$typeMessageCallback,
$identifier,
'variable',
$line,
);
}
}
return $this->errorBuilder(sprintf('Variable $%s %s is never defined.', $link->getVariableName(), $operatorDescription), $line)
->identifier(sprintf('%s.variable', $identifier))
->build();
}
return $error;
}
if ($link->isOffset()) {
$type = $link->getVarType();
if (!$link->getIsOffsetAccessible()->yes()) {
return $error ?? $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
$dimType = $link->getDimType();
$hasOffsetValue = $link->getHasOffsetValue();
if ($hasOffsetValue->no()) {
if (!$this->checkAdvancedIsset) {
return null;
}
return $this->errorBuilder(
sprintf(
'Offset %s on %s %s does not exist.',
$dimType->describe(VerbosityLevel::value()),
$type->describe(VerbosityLevel::value()),
$operatorDescription,
),
$line,
)->identifier(sprintf('%s.offset', $identifier))->build();
}
// If offset cannot be null, store this error message and see if one of the earlier offsets is.
// E.g. $array['a']['b']['c'] ?? null; is a valid coalesce if a OR b or C might be null.
if ($hasOffsetValue->yes() || $link->hasExpressionTypeOfExpr()) {
if (!$this->checkAdvancedIsset) {
return null;
}
$error ??= $this->generateError($link->getValueType(), sprintf(
'Offset %s on %s %s always exists and',
$dimType->describe(VerbosityLevel::value()),
$type->describe(VerbosityLevel::value()),
$operatorDescription,
), $typeMessageCallback, $identifier, 'offset', $line);
if ($error !== null) {
return $inner !== null ? $this->doCheck($inner, $scope, $operatorDescription, $identifier, $typeMessageCallback, $error, $line) : $error;
}
}
// Has offset, it is nullable
return null;
}
if ($link->isProperty()) {
$reflection = $link->getPropertyReflection();
$propertyFetch = $link->getPropertyFetch();
if ($reflection === null || !$link->isReflectionNative()) {
return $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
if ($link->hasNativeType() && !$link->isVirtual()->yes()) {
if ($link->isInitializedThisProperty()) {
return $this->generateError(
$link->getNativeType(),
sprintf('%s %s', $this->propertyDescriptor->describeProperty($reflection, $scope, $propertyFetch), $operatorDescription),
static function (Type $type) use ($typeMessageCallback): ?string {
$originalMessage = $typeMessageCallback($type);
if ($originalMessage === null) {
return null;
}
if (str_starts_with($originalMessage, 'is not')) {
return sprintf('%s nor uninitialized', $originalMessage);
}
return sprintf('%s and initialized', $originalMessage);
},
$identifier,
'initializedProperty',
$line,
);
}
if (
!$link->hasExpressionTypeOfFetch()
&& $link->nativeReflectionExists()
&& !$link->nativeHasDefaultValue()
&& (!$link->nativeIsPromoted() || (!$link->nativeIsReadOnly() && !$link->nativeIsHooked()))
) {
return null;
}
}
$propertyDescription = $this->propertyDescriptor->describeProperty($reflection, $scope, $propertyFetch);
$propertyType = $reflection->getWritableType();
if ($error !== null) {
return $inner !== null
? $this->doCheck($inner, $scope, $operatorDescription, $identifier, $typeMessageCallback, $error, $line)
: $error;
}
if (!$this->checkAdvancedIsset) {
return $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
$error = $this->generateError(
$propertyType,
sprintf('%s (%s) %s', $propertyDescription, $propertyType->describe(VerbosityLevel::typeOnly()), $operatorDescription),
$typeMessageCallback,
$identifier,
'property',
$line,
);
if ($error !== null && $inner !== null) {
return $this->doCheck($inner, $scope, $operatorDescription, $identifier, $typeMessageCallback, $error, $line);
}
return $error;
}
// leaf - an arbitrary base expression that is not a chain link
if ($error !== null) {
return $error;
}
if (!$this->checkAdvancedIsset) {
return null;
}
$error = $this->generateError(
$link->getValueType(),
sprintf('Expression %s', $operatorDescription),
$typeMessageCallback,
$identifier,
'expr',
$line,
);
if ($error !== null) {
return $error;
}
if ($link->leafIsNullsafePropertyFetch()) {
$leafExpr = $link->getLeafExpr();
if ($leafExpr instanceof NullsafePropertyFetch && $leafExpr->name instanceof Identifier) {
return $this->errorBuilder(sprintf('Using nullsafe property access "?->%s" %s is unnecessary. Use -> instead.', $leafExpr->name->name, $operatorDescription), $line)
->identifier('nullsafe.neverNull')
->build();
}
return $this->errorBuilder(sprintf('Using nullsafe property access "?->(Expression)" %s is unnecessary. Use -> instead.', $operatorDescription), $line)
->identifier('nullsafe.neverNull')
->build();
}
return null;
}
/**
* @param ErrorIdentifier $identifier
*/
private function checkUndefinedInner(?IssetabilityResolution $resolution, MutatingScope $scope, string $operatorDescription, string $identifier, ?int $line): ?IdentifierRuleError
{
if ($resolution === null) {
return null;
}
$link = $resolution->getLink();
$inner = $resolution->getInner();
if ($link->isVariable()) {
if (!$link->getHasVariable()->no()) {
return null;
}
return $this->errorBuilder(sprintf('Variable $%s %s is never defined.', $link->getVariableName(), $operatorDescription), $line)
->identifier(sprintf('%s.variable', $identifier))
->build();
}
if ($link->isOffset()) {
if (!$link->getIsOffsetAccessible()->yes()) {
return $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
if (!$link->getHasOffsetValue()->no()) {
return $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
return $this->errorBuilder(
sprintf(
'Offset %s on %s %s does not exist.',
$link->getDimType()->describe(VerbosityLevel::value()),
$link->getVarType()->describe(VerbosityLevel::value()),
$operatorDescription,
),
$line,
)->identifier(sprintf('%s.offset', $identifier))->build();
}
if ($link->isProperty()) {
return $this->checkUndefinedInner($inner, $scope, $operatorDescription, $identifier, $line);
}
return null;
}
/**
* @param callable(Type): ?string $typeMessageCallback
* @param ErrorIdentifier $identifier
* @param 'variable'|'offset'|'property'|'expr'|'initializedProperty' $identifierSecondPart
*/
private function generateError(Type $type, string $message, callable $typeMessageCallback, string $identifier, string $identifierSecondPart, ?int $line): ?IdentifierRuleError
{
$typeMessage = $typeMessageCallback($type);
if ($typeMessage === null) {
return null;
}
return $this->errorBuilder(
sprintf('%s %s.', $message, $typeMessage),
$line,
)->identifier(sprintf('%s.%s', $identifier, $identifierSecondPart))->build();
}
/**
* @return RuleErrorBuilder<RuleError>
*/
private function errorBuilder(string $message, ?int $line): RuleErrorBuilder
{
$builder = RuleErrorBuilder::message($message);
if ($line === null) {
return $builder;
}
return $builder->line($line);
}
}