forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonexistentOffsetInArrayDimFetchRule.php
More file actions
268 lines (230 loc) · 7.65 KB
/
NonexistentOffsetInArrayDimFetchRule.php
File metadata and controls
268 lines (230 loc) · 7.65 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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Arrays;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\NullsafeOperatorHelper;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Internal\SprintfHelper;
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function count;
use function in_array;
use function is_string;
use function sprintf;
/**
* @implements Rule<Node\Expr\ArrayDimFetch>
*/
#[RegisteredRule(level: 3)]
final class NonexistentOffsetInArrayDimFetchRule implements Rule
{
public function __construct(
private RuleLevelHelper $ruleLevelHelper,
private NonexistentOffsetInArrayDimFetchCheck $nonexistentOffsetInArrayDimFetchCheck,
private ExprPrinter $exprPrinter,
#[AutowiredParameter]
private bool $reportMaybes,
)
{
}
public function getNodeType(): string
{
return Node\Expr\ArrayDimFetch::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($this->isImplicitArrayCreation($node, $scope)->yes()) {
return [];
}
if ($node->dim !== null) {
$dimType = $scope->getType($node->dim);
$unknownClassPattern = sprintf('Access to offset %s on an unknown class %%s.', SprintfHelper::escapeFormatString($dimType->describe(VerbosityLevel::value())));
} else {
$dimType = null;
$unknownClassPattern = 'Access to an offset on an unknown class %s.';
}
$isOffsetAccessibleTypeResult = $this->ruleLevelHelper->findTypeToCheck(
$scope,
NullsafeOperatorHelper::getNullsafeShortcircuitedExprRespectingScope($scope, $node->var),
$unknownClassPattern,
static fn (Type $type): bool => $type->isOffsetAccessible()->yes(),
);
$isOffsetAccessibleType = $isOffsetAccessibleTypeResult->getType();
if ($isOffsetAccessibleType instanceof ErrorType) {
return $isOffsetAccessibleTypeResult->getUnknownClassErrors();
}
if ($scope->hasExpressionType($node)->yes()) {
return [];
}
$isOffsetAccessible = $isOffsetAccessibleType->isOffsetAccessible();
if ($scope->isInExpressionAssign($node) && $isOffsetAccessible->yes()) {
return [];
}
if ($scope->isUndefinedExpressionAllowed($node) && $isOffsetAccessibleType->isOffsetAccessLegal()->yes()) {
return [];
}
if (!$isOffsetAccessible->yes()) {
if ($isOffsetAccessible->no() || $this->reportMaybes) {
if ($dimType !== null) {
return [
RuleErrorBuilder::message(sprintf(
'Cannot access offset %s on %s.',
$dimType->describe(count($dimType->getConstantStrings()) > 0 ? VerbosityLevel::precise() : VerbosityLevel::value()),
$isOffsetAccessibleType->describe(VerbosityLevel::value()),
))->identifier('offsetAccess.nonOffsetAccessible')->build(),
];
}
return [
RuleErrorBuilder::message(sprintf(
'Cannot access an offset on %s.',
$isOffsetAccessibleType->describe(VerbosityLevel::typeOnly()),
))->identifier('offsetAccess.nonOffsetAccessible')->build(),
];
}
return [];
}
if ($dimType === null) {
return [];
}
if (
$node->dim instanceof Node\Expr\FuncCall
&& !$node->dim->isFirstClassCallable()
&& $node->dim->name instanceof Node\Name
&& in_array($node->dim->name->toLowerString(), ['array_key_first', 'array_key_last'], true)
&& count($node->dim->getArgs()) >= 1
) {
$arrayArg = $node->dim->getArgs()[0]->value;
$arrayType = $scope->getType($arrayArg);
if (
$this->isDeterministicExpr($node->var, $scope)
&& $this->exprPrinter->printExpr($arrayArg) === $this->exprPrinter->printExpr($node->var)
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
}
}
if (
$node->dim instanceof Node\Expr\FuncCall
&& $node->dim->name instanceof Node\Name
&& $node->dim->name->toLowerString() === 'array_rand'
&& count($node->dim->getArgs()) >= 1
) {
$numArg = null;
$arrayArg = $node->dim->getArgs()[0]->value;
if (count($node->dim->getArgs()) > 1) {
$numArg = $node->dim->getArgs()[1]->value;
}
$one = new ConstantIntegerType(1);
$arrayType = $scope->getType($arrayArg);
if (
$this->isDeterministicExpr($node->var, $scope)
&& $this->exprPrinter->printExpr($arrayArg) === $this->exprPrinter->printExpr($node->var)
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
&& ($numArg === null || $one->isSuperTypeOf($scope->getType($numArg))->yes())
) {
return [];
}
}
if (
$node->dim instanceof Node\Expr\BinaryOp\Minus
&& $node->dim->left instanceof Node\Expr\FuncCall
&& $node->dim->left->name instanceof Node\Name
&& in_array($node->dim->left->name->toLowerString(), ['count', 'sizeof'], true)
&& count($node->dim->left->getArgs()) >= 1
&& $node->dim->right instanceof Node\Scalar\Int_
&& $node->dim->right->value === 1
) {
$arrayArg = $node->dim->left->getArgs()[0]->value;
$arrayType = $scope->getType($arrayArg);
if (
$this->isDeterministicExpr($node->var, $scope)
&& $this->exprPrinter->printExpr($arrayArg) === $this->exprPrinter->printExpr($node->var)
&& $arrayType->isList()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
}
}
return $this->nonexistentOffsetInArrayDimFetchCheck->check(
$scope,
$node->var,
$unknownClassPattern,
$dimType,
);
}
private function isDeterministicExpr(Expr $expr, Scope $scope): bool
{
if ($expr instanceof Variable) {
return true;
}
if ($expr instanceof Expr\PropertyFetch) {
return $this->isDeterministicExpr($expr->var, $scope);
}
if ($expr instanceof Expr\StaticPropertyFetch) {
return true;
}
if ($expr instanceof Expr\ArrayDimFetch) {
if ($expr->dim === null) {
return false;
}
return $this->isDeterministicExpr($expr->var, $scope)
&& $this->isDeterministicExpr($expr->dim, $scope);
}
if ($expr instanceof Expr\MethodCall && $expr->name instanceof Node\Identifier) {
$callerType = $scope->getType($expr->var);
$methodReflection = $scope->getMethodReflection($callerType, $expr->name->name);
if ($methodReflection !== null && $methodReflection->hasSideEffects()->no()) {
return $this->isDeterministicExpr($expr->var, $scope)
&& $this->areDeterministicArgs($expr->getArgs(), $scope);
}
return false;
}
if ($expr instanceof Expr\StaticCall && $expr->name instanceof Node\Identifier && $expr->class instanceof Node\Name) {
$classType = $scope->resolveTypeByName($expr->class);
$methodReflection = $scope->getMethodReflection($classType, $expr->name->name);
if ($methodReflection !== null && $methodReflection->hasSideEffects()->no()) {
return $this->areDeterministicArgs($expr->getArgs(), $scope);
}
return false;
}
return false;
}
/**
* @param Node\Arg[] $args
*/
private function areDeterministicArgs(array $args, Scope $scope): bool
{
foreach ($args as $arg) {
if (!$this->isDeterministicExpr($arg->value, $scope)) {
return false;
}
}
return true;
}
private function isImplicitArrayCreation(Node\Expr\ArrayDimFetch $node, Scope $scope): TrinaryLogic
{
$varNode = $node->var;
while ($varNode instanceof ArrayDimFetch) {
$varNode = $varNode->var;
}
if (!$varNode instanceof Variable) {
return TrinaryLogic::createNo();
}
if (!is_string($varNode->name)) {
return TrinaryLogic::createNo();
}
return $scope->hasVariableType($varNode->name)->negate();
}
}