forked from larastan/larastan
/
NoUnnecessaryCollectionCallRule.php
363 lines (318 loc) · 11.3 KB
/
NoUnnecessaryCollectionCallRule.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
declare(strict_types=1);
namespace NunoMaduro\Larastan\Rules;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use NunoMaduro\Larastan\Properties\ModelPropertyExtension;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
/**
* This rule checks for unnecessary heavy operations on the Collection class
* that could have instead been performed on the Builder class.
*
* For example:
* User::all()->count()
* could be simplified to:
* User::count()
*
* In addition, this code:
* User::whereStatus('active')->get()->pluck('id')
* could be simplified to:
* User::whereStatus('active')->pluck('id')
*
* @implements Rule<MethodCall>
*/
class NoUnnecessaryCollectionCallRule implements Rule
{
/**
* The method names that can be applied on a Collection, but should be applied on a Builder.
*
* @var string[]
*/
protected const RISKY_METHODS = [
'count',
'isempty',
'isnotempty',
'last',
'pop',
'skip',
'slice',
'take',
// Eloquent collection
'diff',
'except',
'find',
'modelkeys',
'only',
];
/**
* The method names that can be applied on a Collection, but should in some cases be applied
* on a builder depending on what parameter is passed to the method.
*
* @var string[]
*/
protected const RISKY_PARAM_METHODS = [
'average',
'avg',
'firstwhere',
'max',
'min',
'pluck',
'sum',
'where',
'wherestrict',
];
/** @var string[] The method names that should be checked by this rule - can be configured by the user. */
protected $shouldHandle;
/**
* @var \PHPStan\Reflection\ReflectionProvider
*/
protected $reflectionProvider;
/**
* @var \NunoMaduro\Larastan\Properties\ModelPropertyExtension
*/
protected $propertyExtension;
/**
* NoRedundantCollectionCallRule constructor.
*
* @param ReflectionProvider $reflectionProvider
* @param ModelPropertyExtension $propertyExtension
* @param string[] $onlyMethods
* @param string[] $excludeMethods
*/
public function __construct(
ReflectionProvider $reflectionProvider,
ModelPropertyExtension $propertyExtension,
array $onlyMethods,
array $excludeMethods
) {
$this->reflectionProvider = $reflectionProvider;
$this->propertyExtension = $propertyExtension;
$allMethods = array_merge(
static::RISKY_METHODS,
static::RISKY_PARAM_METHODS,
[
'first',
'contains',
'containsstrict',
]
);
if (! empty($onlyMethods)) {
$this->shouldHandle = array_map(function (string $methodName): string {
return Str::lower($methodName);
}, $onlyMethods);
} else {
$this->shouldHandle = $allMethods;
}
if (! empty($excludeMethods)) {
$this->shouldHandle = array_diff($this->shouldHandle, array_map(function (string $methodName): string {
return Str::lower($methodName);
}, $excludeMethods));
}
}
/**
* @return string
*/
public function getNodeType(): string
{
return MethodCall::class;
}
/**
* @param Node $node
* @param Scope $scope
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
/** @var \PhpParser\Node\Expr\MethodCall $node */
if (! $node->name instanceof Identifier) {
return [];
}
/** @var \PhpParser\Node\Identifier $name */
$name = $node->name;
if (! $this->isCalledOnCollection($node->var, $scope)) {
// Method was not called on a collection, so no errors.
return [];
}
$previousCall = $node->var;
if (! $this->callIsQuery($previousCall, $scope)) {
// Previous call wasn't on a Builder, so no errors.
return [];
}
/** @var Node\Expr\MethodCall|Node\Expr\StaticCall $previousCall */
if (! ($previousCall->name instanceof Identifier)) {
// Previous call was made dynamically e.g. User::query()->{$method}()
// Can't really analyze it in this scenario so no errors.
return [];
}
if (! in_array($name->toLowerString(), $this->shouldHandle, true)) {
return [];
}
if ($name->toLowerString() === 'first') {
if (count($node->args) === 0) {
// 'first', also accepts a closure as an argument.
return [$this->formatError($name->toString())];
}
} elseif ($this->isRiskyMethod($name)) {
return [$this->formatError($name->toString())];
} elseif ($this->isRiskyParamMethod($name)) {
if (count($node->args) === 0) {
// Calling e.g. DB::table()->pluck($columnName)-sum()
// We have to check whether $columnName is actually a database column
// and not an alias for some computed attribute
if ($previousCall->name->name === 'pluck' && $this->firstArgIsDatabaseColumn($previousCall, $scope)) {
return [$this->formatError($name->toString())];
}
return [];
}
if ($this->firstArgIsDatabaseColumn($node, $scope)) {
return [$this->formatError($name->toString())];
}
} elseif (in_array($name->toLowerString(), ['contains', 'containsstrict'], true)) {
// 'contains' can also be called with Model instances or keys as its first argument
/** @var \PhpParser\Node\Arg[] $args */
$args = $node->args;
if (count($args) === 1 && ! ($args[0]->value instanceof Node\FunctionLike)) {
return [$this->formatError($name->toString())];
}
if ($this->firstArgIsDatabaseColumn($node, $scope)) {
return [$this->formatError($name->toString())];
}
}
return [];
}
/**
* Determines whether the first argument is a string and references a database column.
*
* @param Node\Expr\StaticCall|MethodCall $node
* @param Scope $scope
* @return bool
*/
protected function firstArgIsDatabaseColumn($node, Scope $scope): bool
{
/** @var \PhpParser\Node\Arg[] $args */
$args = $node->args;
if (count($args) === 0 || ! ($args[0]->value instanceof Node\Scalar\String_)) {
return false;
}
if ($node instanceof Node\Expr\StaticCall) {
/** @var Node\Name $class */
$class = $node->class;
$modelReflection = $this->reflectionProvider->getClass($class->toCodeString());
/** @var \PhpParser\Node\Scalar\String_ $firstArg */
$firstArg = $args[0]->value;
return $this->propertyExtension->hasProperty($modelReflection, $firstArg->value);
}
$iterableType = $scope->getType($node->var)->getIterableValueType();
if ($iterableType instanceof MixedType) {
$previous_call = $node->var;
if ($previous_call instanceof MethodCall) {
$query_builder_type = $scope->getType($previous_call->var);
if ((new ObjectType(QueryBuilder::class))->isSuperTypeOf($query_builder_type)->yes()) {
// We encountered a DB query such as DB::table(..)->get()->max('id')
// We assume max('id') could have been retrieved without calling get().
return true;
}
}
return false;
}
/** @var \PHPStan\Type\ObjectType $iterableType */
if ((new ObjectType(Model::class))->isSuperTypeOf($iterableType)->yes()) {
$modelReflection = $this->reflectionProvider->getClass($iterableType->getClassName());
/** @var \PhpParser\Node\Scalar\String_ $firstArg */
$firstArg = $args[0]->value;
return $this->propertyExtension->hasProperty($modelReflection, $firstArg->value);
}
return false;
}
/**
* Returns whether the method call is a call on a builder instance.
*
* @param Node\Expr $call
* @param Scope $scope
* @return bool
*/
protected function callIsQuery(Node\Expr $call, Scope $scope): bool
{
if ($call instanceof MethodCall) {
$calledOn = $scope->getType($call->var);
return $this->isBuilder($calledOn);
}
if ($call instanceof Node\Expr\StaticCall) {
/** @var Node\Name $class */
$class = $call->class;
if ($class instanceof Node\Name) {
$modelClassName = $class->toCodeString();
return (new ObjectType(Model::class))->isSuperTypeOf(new ObjectType($modelClassName))->yes()
&& $call->name instanceof Identifier
&& in_array($call->name->toLowerString(), ['get', 'all', 'pluck'], true);
}
}
return false;
}
/**
* Returns whether the method is one of the risky methods.
*
* @param Identifier $name
* @return bool
*/
protected function isRiskyMethod(Identifier $name): bool
{
return in_array($name->toLowerString(), self::RISKY_METHODS, true);
}
/**
* Returns whether the method might be a risky method depending on the parameters passed.
*
* @param Identifier $name
* @return bool
*/
protected function isRiskyParamMethod(Identifier $name): bool
{
return in_array($name->toLowerString(), self::RISKY_PARAM_METHODS, true);
}
/**
* Returns whether its argument is some builder instance.
*
* @param Type $type
* @return bool
*/
protected function isBuilder(Type $type): bool
{
return (new ObjectType(EloquentBuilder::class))->isSuperTypeOf($type)->yes()
|| (new ObjectType(QueryBuilder::class))->isSuperTypeOf($type)->yes()
|| (new ObjectType(Relation::class))->isSuperTypeOf($type)->yes();
}
/**
* Returns whether the Expr was not called on a Collection instance.
*
* @param Node\Expr $expr
* @param Scope $scope
* @return bool
*/
protected function isCalledOnCollection(Node\Expr $expr, Scope $scope): bool
{
$calledOnType = $scope->getType($expr);
return (new ObjectType(Collection::class))->isSuperTypeOf($calledOnType)->yes();
}
/**
* Formats the error.
*
* @param string $method_name
* @return string
*/
protected function formatError(string $method_name): string
{
return "Called '{$method_name}' on Laravel collection, but could have been retrieved as a query.";
}
}