forked from phpstan/phpstan-phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataProviderHelper.php
More file actions
358 lines (310 loc) · 9.67 KB
/
DataProviderHelper.php
File metadata and controls
358 lines (310 loc) · 9.67 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
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
<?php declare(strict_types = 1);
namespace PHPStan\Rules\PHPUnit;
use PhpParser\Comment\Doc;
use PhpParser\Modifiers;
use PhpParser\Node\Attribute;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\NodeFinder;
use PHPStan\Analyser\Scope;
use PHPStan\Parser\Parser;
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MissingMethodFromReflectionException;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\FileTypeMapper;
use ReflectionMethod;
use function array_merge;
use function count;
use function explode;
use function method_exists;
use function preg_match;
use function sprintf;
class DataProviderHelper
{
private ReflectionProvider $reflectionProvider;
private FileTypeMapper $fileTypeMapper;
private Parser $parser;
private bool $phpunit10OrNewer;
public function __construct(
ReflectionProvider $reflectionProvider,
FileTypeMapper $fileTypeMapper,
Parser $parser,
bool $phpunit10OrNewer
)
{
$this->reflectionProvider = $reflectionProvider;
$this->fileTypeMapper = $fileTypeMapper;
$this->parser = $parser;
$this->phpunit10OrNewer = $phpunit10OrNewer;
}
/**
* @param ReflectionMethod|ClassMethod $node
*
* @return iterable<array{ClassReflection|null, string, int}>
*/
public function getDataProviderMethods(
Scope $scope,
$node,
ClassReflection $classReflection
): iterable
{
yield from $this->yieldDataProviderAnnotations($node, $scope, $classReflection);
if (!$this->phpunit10OrNewer) {
return;
}
yield from $this->yieldDataProviderAttributes($node, $classReflection);
}
/**
* @return array<PhpDocTagNode>
*/
private function getDataProviderAnnotations(?ResolvedPhpDocBlock $phpDoc): array
{
if ($phpDoc === null) {
return [];
}
$phpDocNodes = $phpDoc->getPhpDocNodes();
$annotations = [];
foreach ($phpDocNodes as $docNode) {
$annotations = array_merge(
$annotations,
$docNode->getTagsByName('@dataProvider'),
);
}
return $annotations;
}
/**
* @return list<IdentifierRuleError> errors
*/
public function processDataProvider(
string $dataProviderValue,
?ClassReflection $classReflection,
string $methodName,
int $lineNumber,
bool $checkFunctionNameCase,
bool $deprecationRulesInstalled
): array
{
if ($classReflection === null) {
return [
RuleErrorBuilder::message(sprintf(
'@dataProvider %s related class not found.',
$dataProviderValue,
))
->line($lineNumber)
->identifier('phpunit.dataProviderClass')
->build(),
];
}
try {
$dataProviderMethodReflection = $classReflection->getNativeMethod($methodName);
} catch (MissingMethodFromReflectionException $missingMethodFromReflectionException) {
return [
RuleErrorBuilder::message(sprintf(
'@dataProvider %s related method not found.',
$dataProviderValue,
))
->line($lineNumber)
->identifier('phpunit.dataProviderMethod')
->build(),
];
}
$errors = [];
if ($checkFunctionNameCase && $methodName !== $dataProviderMethodReflection->getName()) {
$errors[] = RuleErrorBuilder::message(sprintf(
'@dataProvider %s related method is used with incorrect case: %s.',
$dataProviderValue,
$dataProviderMethodReflection->getName(),
))
->line($lineNumber)
->identifier('method.nameCase')
->build();
}
if (!$dataProviderMethodReflection->isPublic()) {
$errors[] = RuleErrorBuilder::message(sprintf(
'@dataProvider %s related method must be public.',
$dataProviderValue,
))
->line($lineNumber)
->identifier('phpunit.dataProviderPublic')
->build();
}
if ($deprecationRulesInstalled && $this->phpunit10OrNewer && !$dataProviderMethodReflection->isStatic()) {
$errorBuilder = RuleErrorBuilder::message(sprintf(
'@dataProvider %s related method must be static in PHPUnit 10 and newer.',
$dataProviderValue,
))
->line($lineNumber)
->identifier('phpunit.dataProviderStatic');
$dataProviderMethodReflectionDeclaringClass = $dataProviderMethodReflection->getDeclaringClass();
if ($dataProviderMethodReflectionDeclaringClass->getFileName() !== null) {
$stmts = $this->parser->parseFile($dataProviderMethodReflectionDeclaringClass->getFileName());
$nodeFinder = new NodeFinder();
/** @var ClassMethod|null $methodNode */
$methodNode = $nodeFinder->findFirst($stmts, static fn ($node) => $node instanceof ClassMethod && $node->name->toString() === $dataProviderMethodReflection->getName());
if ($methodNode !== null) {
$errorBuilder->fixNode($methodNode, static function (ClassMethod $methodNode) {
$methodNode->flags |= Modifiers::STATIC;
return $methodNode;
});
}
}
$errors[] = $errorBuilder->build();
}
return $errors;
}
private function getDataProviderAnnotationValue(PhpDocTagNode $phpDocTag): ?string
{
if (preg_match('/^[^ \t]+/', (string) $phpDocTag->value, $matches) !== 1) {
return null;
}
return $matches[0];
}
/**
* @return array{ClassReflection|null, string}
*/
private function parseDataProviderAnnotationValue(Scope $scope, string $dataProviderValue): array
{
$parts = explode('::', $dataProviderValue, 2);
if (count($parts) <= 1) {
return [$scope->getClassReflection(), $dataProviderValue];
}
if ($this->reflectionProvider->hasClass($parts[0])) {
return [$this->reflectionProvider->getClass($parts[0]), $parts[1]];
}
return [null, $dataProviderValue];
}
/**
* @return array<string, array{(ClassReflection|null), string, int}>|null
*/
private function parseDataProviderExternalAttribute(Attribute $attribute): ?array
{
if (count($attribute->args) !== 2) {
return null;
}
$methodNameArg = $attribute->args[1]->value;
if (!$methodNameArg instanceof String_) {
return null;
}
$classNameArg = $attribute->args[0]->value;
if ($classNameArg instanceof ClassConstFetch && $classNameArg->class instanceof Name) {
$className = $classNameArg->class->toString();
} elseif ($classNameArg instanceof String_) {
$className = $classNameArg->value;
} else {
return null;
}
$dataProviderClassReflection = null;
if ($this->reflectionProvider->hasClass($className)) {
$dataProviderClassReflection = $this->reflectionProvider->getClass($className);
$className = $dataProviderClassReflection->getName();
}
return [
sprintf('%s::%s', $className, $methodNameArg->value) => [
$dataProviderClassReflection,
$methodNameArg->value,
$attribute->getStartLine(),
],
];
}
/**
* @return array<string, array{ClassReflection, string, int}>|null
*/
private function parseDataProviderAttribute(Attribute $attribute, ClassReflection $classReflection): ?array
{
if (count($attribute->args) !== 1) {
return null;
}
$methodNameArg = $attribute->args[0]->value;
if (!$methodNameArg instanceof String_) {
return null;
}
return [
$methodNameArg->value => [
$classReflection,
$methodNameArg->value,
$attribute->getStartLine(),
],
];
}
/**
* @param ReflectionMethod|ClassMethod $node
*
* @return iterable<array{ClassReflection|null, string, int}>
*/
private function yieldDataProviderAttributes($node, ClassReflection $classReflection): iterable
{
if (
$node instanceof ReflectionMethod
) {
/** @phpstan-ignore function.alreadyNarrowedType */
if (!method_exists($node, 'getAttributes')) {
return;
}
foreach ($node->getAttributes('PHPUnit\Framework\Attributes\DataProvider') as $attr) {
$args = $attr->getArguments();
if (count($args) !== 1) {
continue;
}
$startLine = $node->getStartLine();
if ($startLine === false) {
$startLine = -1;
}
yield [$classReflection, $args[0], $startLine];
}
return;
}
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$dataProviderMethod = null;
if ($attr->name->toLowerString() === 'phpunit\\framework\\attributes\\dataprovider') {
$dataProviderMethod = $this->parseDataProviderAttribute($attr, $classReflection);
} elseif ($attr->name->toLowerString() === 'phpunit\\framework\\attributes\\dataproviderexternal') {
$dataProviderMethod = $this->parseDataProviderExternalAttribute($attr);
}
if ($dataProviderMethod === null) {
continue;
}
yield from $dataProviderMethod;
}
}
}
/**
* @param ReflectionMethod|ClassMethod $node
*
* @return iterable<array{ClassReflection|null, string, int}>
*/
private function yieldDataProviderAnnotations($node, Scope $scope, ClassReflection $classReflection): iterable
{
$docComment = $node->getDocComment();
if ($docComment === null || $docComment === false) {
return;
}
$methodPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
$scope->getFile(),
$classReflection->getName(),
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
$node instanceof ClassMethod ? $node->name->toString() : $node->getName(),
$docComment instanceof Doc ? $docComment->getText() : $docComment,
);
foreach ($this->getDataProviderAnnotations($methodPhpDoc) as $annotation) {
$dataProviderValue = $this->getDataProviderAnnotationValue($annotation);
if ($dataProviderValue === null) {
// Missing value is already handled in NoMissingSpaceInMethodAnnotationRule
continue;
}
$startLine = $node->getStartLine();
if ($startLine === false) {
$startLine = -1;
}
$dataProviderMethod = $this->parseDataProviderAnnotationValue($scope, $dataProviderValue);
$dataProviderMethod[] = $startLine;
yield $dataProviderValue => $dataProviderMethod;
}
}
}