/
NoModelMakeRule.php
113 lines (100 loc) · 2.88 KB
/
NoModelMakeRule.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
<?php
declare(strict_types=1);
namespace NunoMaduro\Larastan\Rules;
use Illuminate\Database\Eloquent\Model;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name\FullyQualified;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeUtils;
/**
* Catches inefficient instantiation of models using Model::make().
*
* For example:
* User::make()
*
* It is functionally equivalent to simply use the constructor:
* new User()
*
* @implements Rule<MethodCall>
*/
class NoModelMakeRule implements Rule
{
/**
* @var \PHPStan\Reflection\ReflectionProvider
*/
protected $reflectionProvider;
/**
* @param ReflectionProvider $reflectionProvider
*/
public function __construct(ReflectionProvider $reflectionProvider)
{
$this->reflectionProvider = $reflectionProvider;
}
/**
* @return string
*/
public function getNodeType(): string
{
return StaticCall::class;
}
/**
* @param Node $node
* @param Scope $scope
* @return array<int, RuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
/** @var StaticCall $node due to @see getNodeType() */
$name = $node->name;
if (! $name instanceof Identifier) {
return [];
}
if ($name->name !== 'make') {
return [];
}
if (! $this->isCalledOnModel($node, $scope)) {
return [];
}
return [
RuleErrorBuilder::message("Called 'Model::make()' which performs unnecessary work, use 'new Model()'.")
->identifier('rules.noModelMake')
->line($node->getLine())
->file($scope->getFile())
->build(),
];
}
/**
* Was the expression called on a Model instance?
*
* @param StaticCall $call
* @param Scope $scope
* @return bool
*/
protected function isCalledOnModel(StaticCall $call, Scope $scope): bool
{
$class = $call->class;
if ($class instanceof FullyQualified) {
$type = new ObjectType($class->toString());
} elseif ($class instanceof Expr) {
$type = $scope->getType($class);
if ($type->isClassStringType()->yes() && TypeUtils::getConstantStrings($type) !== []) {
$type = new ObjectType($type->getValue()); // @phpstan-ignore-line
}
} else {
// TODO can we handle relative names, do they even occur here?
return false;
}
return (new ObjectType(Model::class))
->isSuperTypeOf($type)
->yes();
}
}