-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathInstantiationRule.php
263 lines (236 loc) · 8.15 KB
/
InstantiationRule.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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Classes;
use PhpParser\Node;
use PhpParser\Node\Expr\New_;
use PHPStan\Analyser\Scope;
use PHPStan\Internal\SprintfHelper;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\Php\PhpMethodReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\ClassNameCheck;
use PHPStan\Rules\ClassNameNodePair;
use PHPStan\Rules\FunctionCallParametersCheck;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Constant\ConstantStringType;
use function array_map;
use function array_merge;
use function count;
use function sprintf;
use function strtolower;
/**
* @implements Rule<Node\Expr\New_>
*/
final class InstantiationRule implements Rule
{
public function __construct(
private ReflectionProvider $reflectionProvider,
private FunctionCallParametersCheck $check,
private ClassNameCheck $classCheck,
)
{
}
public function getNodeType(): string
{
return New_::class;
}
public function processNode(Node $node, Scope $scope): array
{
$errors = [];
foreach ($this->getClassNames($node, $scope) as [$class, $isName]) {
$errors = array_merge($errors, $this->checkClassName($class, $isName, $node, $scope));
}
return $errors;
}
/**
* @param Node\Expr\New_ $node
* @return list<IdentifierRuleError>
*/
private function checkClassName(string $class, bool $isName, Node $node, Scope $scope): array
{
$lowercasedClass = strtolower($class);
$messages = [];
$isStatic = false;
if ($lowercasedClass === 'static') {
if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf('Using %s outside of class scope.', $class))
->identifier('outOfClass.static')
->build(),
];
}
$isStatic = true;
$classReflection = $scope->getClassReflection();
if (!$classReflection->isFinal()) {
if (!$classReflection->hasConstructor()) {
return [];
}
$constructor = $classReflection->getConstructor();
if (
!$constructor->getPrototype()->getDeclaringClass()->isInterface()
&& $constructor instanceof PhpMethodReflection
&& !$constructor->isFinal()->yes()
&& !$constructor->getPrototype()->isAbstract()
) {
return [];
}
}
} elseif ($lowercasedClass === 'self') {
if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf('Using %s outside of class scope.', $class))
->identifier('outOfClass.self')
->build(),
];
}
$classReflection = $scope->getClassReflection();
} elseif ($lowercasedClass === 'parent') {
if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf('Using %s outside of class scope.', $class))
->identifier('outOfClass.parent')
->build(),
];
}
if ($scope->getClassReflection()->getParentClass() === null) {
return [
RuleErrorBuilder::message(sprintf(
'%s::%s() calls new parent but %s does not extend any class.',
$scope->getClassReflection()->getDisplayName(),
$scope->getFunctionName(),
$scope->getClassReflection()->getDisplayName(),
))->identifier('class.noParent')->build(),
];
}
$classReflection = $scope->getClassReflection()->getParentClass();
} else {
if (!$this->reflectionProvider->hasClass($class)) {
if ($scope->isInClassExists($class)) {
return [];
}
return [
RuleErrorBuilder::message(sprintf('Instantiated class %s not found.', $class))
->identifier('class.notFound')
->discoveringSymbolsTip()
->build(),
];
}
$messages = $this->classCheck->checkClassNames([
new ClassNameNodePair($class, $node->class),
]);
$classReflection = $this->reflectionProvider->getClass($class);
}
if ($classReflection->isEnum() && $isName) {
return [
RuleErrorBuilder::message(
sprintf('Cannot instantiate enum %s.', $classReflection->getDisplayName()),
)->identifier('new.enum')->build(),
];
}
if (!$isStatic && $classReflection->isInterface() && $isName) {
return [
RuleErrorBuilder::message(
sprintf('Cannot instantiate interface %s.', $classReflection->getDisplayName()),
)->identifier('new.interface')->build(),
];
}
if (!$isStatic && $classReflection->isAbstract() && $isName) {
return [
RuleErrorBuilder::message(
sprintf('Instantiated class %s is abstract.', $classReflection->getDisplayName()),
)->identifier('new.abstract')->build(),
];
}
if (!$isName) {
return [];
}
if (!$classReflection->hasConstructor()) {
if (count($node->getArgs()) > 0) {
return array_merge($messages, [
RuleErrorBuilder::message(sprintf(
'Class %s does not have a constructor and must be instantiated without any parameters.',
$classReflection->getDisplayName(),
))->identifier('new.noConstructor')->build(),
]);
}
return $messages;
}
$constructorReflection = $classReflection->getConstructor();
if (!$scope->canCallMethod($constructorReflection)) {
$messages[] = RuleErrorBuilder::message(sprintf(
'Cannot instantiate class %s via %s constructor %s::%s().',
$classReflection->getDisplayName(),
$constructorReflection->isPrivate() ? 'private' : 'protected',
$constructorReflection->getDeclaringClass()->getDisplayName(),
$constructorReflection->getName(),
))
->identifier(sprintf('new.%sConstructor', $constructorReflection->isPrivate() ? 'private' : 'protected'))
->build();
}
$classDisplayName = SprintfHelper::escapeFormatString($classReflection->getDisplayName());
return array_merge($messages, $this->check->check(
ParametersAcceptorSelector::selectFromArgs(
$scope,
$node->getArgs(),
$constructorReflection->getVariants(),
$constructorReflection->getNamedArgumentsVariants(),
),
$scope,
$constructorReflection->getDeclaringClass()->isBuiltin(),
$node,
[
'Class ' . $classDisplayName . ' constructor invoked with %d parameter, %d required.',
'Class ' . $classDisplayName . ' constructor invoked with %d parameters, %d required.',
'Class ' . $classDisplayName . ' constructor invoked with %d parameter, at least %d required.',
'Class ' . $classDisplayName . ' constructor invoked with %d parameters, at least %d required.',
'Class ' . $classDisplayName . ' constructor invoked with %d parameter, %d-%d required.',
'Class ' . $classDisplayName . ' constructor invoked with %d parameters, %d-%d required.',
'Parameter %s of class ' . $classDisplayName . ' constructor expects %s, %s given.',
'', // constructor does not have a return type
'Parameter %s of class ' . $classDisplayName . ' constructor is passed by reference, so it expects variables only',
'Unable to resolve the template type %s in instantiation of class ' . $classDisplayName,
'Missing parameter $%s in call to ' . $classDisplayName . ' constructor.',
'Unknown parameter $%s in call to ' . $classDisplayName . ' constructor.',
'Return type of call to ' . $classDisplayName . ' constructor contains unresolvable type.',
'Parameter %s of class ' . $classDisplayName . ' constructor contains unresolvable type.',
'Class ' . $classDisplayName . ' constructor invoked with %s, but it\'s not allowed because of @no-named-arguments.',
],
'new',
$constructorReflection->acceptsNamedArguments(),
$constructorReflection,
));
}
/**
* @param Node\Expr\New_ $node
* @return array<int, array{string, bool}>
*/
private function getClassNames(Node $node, Scope $scope): array
{
if ($node->class instanceof Node\Name) {
return [[(string) $node->class, true]];
}
if ($node->class instanceof Node\Stmt\Class_) {
$classNames = $scope->getType($node)->getObjectClassNames();
if ($classNames === []) {
throw new ShouldNotHappenException();
}
return array_map(
static fn (string $className) => [$className, true],
$classNames,
);
}
$type = $scope->getType($node->class);
return array_merge(
array_map(
static fn (ConstantStringType $type): array => [$type->getValue(), true],
$type->getConstantStrings(),
),
array_map(
static fn (string $name): array => [$name, false],
$type->getObjectClassNames(),
),
);
}
}