Debian Codegraph @

lib/3rdParty/composer/symfony/property-info/Extractor/PhpStanExtractor.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\PropertyInfo\Extractor;
13
14 use phpDocumentor\Reflection\Types\ContextFactory;
15 use PHPStan\PhpDocParser\Ast\PhpDoc\InvalidTagValueNode;
16 use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
17 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
18 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
19 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
20 use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
21 use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
22 use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
23 use PHPStan\PhpDocParser\Lexer\Lexer;
24 use PHPStan\PhpDocParser\Parser\ConstExprParser;
25 use PHPStan\PhpDocParser\Parser\PhpDocParser;
26 use PHPStan\PhpDocParser\Parser\TokenIterator;
27 use PHPStan\PhpDocParser\Parser\TypeParser;
28 use PHPStan\PhpDocParser\ParserConfig;
29 use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface;
30 use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
31 use Symfony\Component\PropertyInfo\Type as LegacyType;
32 use Symfony\Component\PropertyInfo\Util\PhpStanTypeHelper;
33 use Symfony\Component\TypeInfo\Exception\UnsupportedException;
34 use Symfony\Component\TypeInfo\Type;
35 use Symfony\Component\TypeInfo\TypeContext\TypeContext;
36 use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;
37 use Symfony\Component\TypeInfo\TypeResolver\StringTypeResolver;
38
39 /**
40 * Extracts data using PHPStan parser.
41 *
42 * @author Baptiste Leduc <[email protected]>
43 */
44 final class PhpStanExtractor implements PropertyDescriptionExtractorInterface, PropertyTypeExtractorInterface, ConstructorArgumentTypeExtractorInterface
45 {
46 private const PROPERTY = 0;
47 private const ACCESSOR = 1;
48 private const MUTATOR = 2;
49
50 private PhpDocParser $phpDocParser;
51 private Lexer $lexer;
52
53 private StringTypeResolver $stringTypeResolver;
54 private TypeContextFactory $typeContextFactory;
55
56 /** @var array<string, array{PhpDocNode|null, int|null, string|null, string|null}> */
57 private array $docBlocks = [];
58 private PhpStanTypeHelper $phpStanTypeHelper;
59 private array $mutatorPrefixes;
60 private array $accessorPrefixes;
61 private array $arrayMutatorPrefixes;
62
63 /** @var array<string, TypeContext> */
64 private array $contexts = [];
65
66 /**
67 * @param list<string>|null $mutatorPrefixes
68 * @param list<string>|null $accessorPrefixes
69 * @param list<string>|null $arrayMutatorPrefixes
70 */
71 public function __construct(?array $mutatorPrefixes = null, ?array $accessorPrefixes = null, ?array $arrayMutatorPrefixes = null, private bool $allowPrivateAccess = true)
72 {
73 if (!class_exists(ContextFactory::class)) {
74 throw new \LogicException(\sprintf('Unable to use the "%s" class as the "phpdocumentor/type-resolver" package is not installed. Try running composer require "phpdocumentor/type-resolver".', __CLASS__));
75 }
76
77 if (!class_exists(PhpDocParser::class)) {
78 throw new \LogicException(\sprintf('Unable to use the "%s" class as the "phpstan/phpdoc-parser" package is not installed. Try running composer require "phpstan/phpdoc-parser".', __CLASS__));
79 }
80
81 $this->phpStanTypeHelper = new PhpStanTypeHelper();
82 $this->mutatorPrefixes = $mutatorPrefixes ?? ReflectionExtractor::$defaultMutatorPrefixes;
83 $this->accessorPrefixes = $accessorPrefixes ?? ReflectionExtractor::$defaultAccessorPrefixes;
84 $this->arrayMutatorPrefixes = $arrayMutatorPrefixes ?? ReflectionExtractor::$defaultArrayMutatorPrefixes;
85
86 if (class_exists(ParserConfig::class)) {
87 $parserConfig = new ParserConfig([]);
88 $this->phpDocParser = new PhpDocParser($parserConfig, new TypeParser($parserConfig, new ConstExprParser($parserConfig)), new ConstExprParser($parserConfig));
89 $this->lexer = new Lexer($parserConfig);
90 } else {
91 $this->phpDocParser = new PhpDocParser(new TypeParser(new ConstExprParser()), new ConstExprParser());
92 $this->lexer = new Lexer();
93 }
94 $this->stringTypeResolver = new StringTypeResolver();
95 $this->typeContextFactory = new TypeContextFactory($this->stringTypeResolver);
96 }
97
98 /**
99 * @deprecated since Symfony 7.3, use "getType" instead
100 */
101 public function getTypes(string $class, string $property, array $context = []): ?array
102 {
103 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getType()" instead.', __METHOD__, self::class);
104
105 /** @var PhpDocNode|null $docNode */
106 [$docNode, $source, $prefix, $declaringClass] = $this->getDocBlock($class, $property);
107 if (null === $docNode) {
108 return null;
109 }
110
111 switch ($source) {
112 case self::PROPERTY:
113 $tag = '@var';
114 break;
115
116 case self::ACCESSOR:
117 $tag = '@return';
118 break;
119
120 case self::MUTATOR:
121 $tag = '@param';
122 break;
123 }
124
125 $parentClass = null;
126 $types = [];
127 foreach ($docNode->getTagsByName($tag) as $tagDocNode) {
128 if ($tagDocNode->value instanceof InvalidTagValueNode) {
129 continue;
130 }
131
132 if (
133 $tagDocNode->value instanceof ParamTagValueNode
134 && null === $prefix
135 && $tagDocNode->value->parameterName !== '$'.$property
136 ) {
137 continue;
138 }
139
140 $typeContext = $this->contexts[$class.'/'.$declaringClass] ??= $this->typeContextFactory->createFromClassName($class, $declaringClass);
141
142 foreach ($this->phpStanTypeHelper->getTypes($tagDocNode->value, $typeContext) as $type) {
143 switch ($type->getClassName()) {
144 case 'self':
145 case 'static':
146 $resolvedClass = $class;
147 break;
148
149 case 'parent':
150 if (false !== $resolvedClass = $parentClass ??= get_parent_class($class)) {
151 break;
152 }
153 // no break
154
155 default:
156 $types[] = $type;
157 continue 2;
158 }
159
160 $types[] = new LegacyType(LegacyType::BUILTIN_TYPE_OBJECT, $type->isNullable(), $resolvedClass, $type->isCollection(), $type->getCollectionKeyTypes(), $type->getCollectionValueTypes());
161 }
162 }
163
164 if (!isset($types[0])) {
165 return null;
166 }
167
168 if (!\in_array($prefix, $this->arrayMutatorPrefixes, true)) {
169 return $types;
170 }
171
172 return [new LegacyType(LegacyType::BUILTIN_TYPE_ARRAY, false, null, true, new LegacyType(LegacyType::BUILTIN_TYPE_INT), $types[0])];
173 }
174
175 /**
176 * @deprecated since Symfony 7.3, use "getTypeFromConstructor" instead
177 *
178 * @return LegacyType[]|null
179 */
180 public function getTypesFromConstructor(string $class, string $property): ?array
181 {
182 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getTypeFromConstructor()" instead.', __METHOD__, self::class);
183
184 if (null === $tagDocNode = $this->getDocBlockFromConstructor($class, $property)) {
185 return $this->getTypes($class, $property);
186 }
187
188 $types = [];
189 foreach ($this->phpStanTypeHelper->getTypes($tagDocNode, $this->typeContextFactory->createFromClassName($class)) as $type) {
190 $types[] = $type;
191 }
192
193 if (!isset($types[0])) {
194 return null;
195 }
196
197 return $types;
198 }
199
200 public function getType(string $class, string $property, array $context = []): ?Type
201 {
202 /** @var PhpDocNode|null $docNode */
203 [$docNode, $source, $prefix, $declaringClass] = $this->getDocBlock($class, $property);
204
205 if (null === $docNode) {
206 return null;
207 }
208
209 $typeContext = $this->typeContextFactory->createFromClassName($class, $declaringClass);
210
211 $tag = match ($source) {
212 self::PROPERTY => '@var',
213 self::ACCESSOR => '@return',
214 self::MUTATOR => '@param',
215 default => 'invalid',
216 };
217
218 $types = [];
219
220 foreach ($docNode->getTagsByName($tag) as $tagDocNode) {
221 if (!$tagDocNode->value instanceof ParamTagValueNode && !$tagDocNode->value instanceof ReturnTagValueNode && !$tagDocNode->value instanceof VarTagValueNode) {
222 continue;
223 }
224
225 if ($tagDocNode->value instanceof ParamTagValueNode && null === $prefix && $tagDocNode->value->parameterName !== '$'.$property) {
226 continue;
227 }
228
229 try {
230 $types[] = $this->stringTypeResolver->resolve((string) $tagDocNode->value->type, $typeContext);
231 } catch (UnsupportedException) {
232 }
233 }
234
235 if (!$type = $types[0] ?? null) {
236 return null;
237 }
238
239 if (!\in_array($prefix, $this->arrayMutatorPrefixes, true)) {
240 return $type;
241 }
242
243 return Type::list($type);
244 }
245
246 public function getTypeFromConstructor(string $class, string $property): ?Type
247 {
248 $declaringClass = $class;
249 if (!$tagDocNode = $this->getDocBlockFromConstructor($declaringClass, $property)) {
250 return $this->getType($class, $property);
251 }
252
253 $typeContext = $this->typeContextFactory->createFromClassName($class, $declaringClass);
254
255 return $this->stringTypeResolver->resolve((string) $tagDocNode->type, $typeContext);
256 }
257
258 public function getShortDescription(string $class, string $property, array $context = []): ?string
259 {
260 /** @var PhpDocNode|null $docNode */
261 [$docNode, $constructorDocNode] = $this->getDocBlockFromProperty($class, $property);
262 if (null === $docNode && null === $constructorDocNode) {
263 return null;
264 }
265
266 if ($docNode && $shortDescription = $this->getShortDescriptionFromDocNode($docNode, $property)) {
267 return $shortDescription;
268 }
269
270 if ($constructorDocNode) {
271 return $this->getShortDescriptionFromDocNode($constructorDocNode, $property);
272 }
273
274 return null;
275 }
276
277 public function getLongDescription(string $class, string $property, array $context = []): ?string
278 {
279 /** @var PhpDocNode|null $docNode */
280 [$docNode, $constructorDocNode] = $this->getDocBlockFromProperty($class, $property);
281 if (null === $docNode && null === $constructorDocNode) {
282 return null;
283 }
284
285 if ($docNode && $longDescription = $this->getDescriptionsFromDocNode($docNode)[1]) {
286 return $longDescription;
287 }
288
289 return $constructorDocNode ? $this->getDescriptionsFromDocNode($constructorDocNode)[1] : null;
290 }
291
292 /**
293 * A docblock is split into a template marker, a short description, an optional long description and a tags section.
294 *
295 * - The template marker is either empty, #@+ or #@-.
296 * - The short description is started from a non-tag character, and until one or multiple newlines.
297 * - The long description (optional) is started from a non-tag character, and until a new line is encountered followed by a tag.
298 * - Tags, and the remaining characters
299 *
300 * This method returns the short and the long descriptions.
301 *
302 * @return array{0: ?string, 1: ?string}
303 */
304 private function getDescriptionsFromDocNode(PhpDocNode $docNode): array
305 {
306 $isTemplateMarker = static fn (PhpDocChildNode $node): bool => $node instanceof PhpDocTextNode && ('#@+' === $node->text || '#@-' === $node->text);
307
308 $shortDescription = '';
309 $longDescription = '';
310 $shortDescriptionCompleted = false;
311
312 // BC layer for phpstan/phpdoc-parser < 2.0
313 if (!class_exists(ParserConfig::class)) {
314 $isNewLine = static fn (PhpDocChildNode $node): bool => $node instanceof PhpDocTextNode && '' === $node->text;
315
316 foreach ($docNode->children as $child) {
317 if (!$child instanceof PhpDocTextNode) {
318 break;
319 }
320
321 if ($isTemplateMarker($child)) {
322 continue;
323 }
324
325 if ($isNewLine($child) && !$shortDescriptionCompleted) {
326 if ($shortDescription) {
327 $shortDescriptionCompleted = true;
328 }
329
330 continue;
331 }
332
333 if (!$shortDescriptionCompleted) {
334 $shortDescription = \sprintf("%s\n%s", $shortDescription, $child->text);
335
336 continue;
337 }
338
339 $longDescription = \sprintf("%s\n%s", $longDescription, $child->text);
340 }
341 } else {
342 foreach ($docNode->children as $child) {
343 if (!$child instanceof PhpDocTextNode) {
344 break;
345 }
346
347 if ($isTemplateMarker($child)) {
348 continue;
349 }
350
351 foreach (explode("\n", $child->text) as $line) {
352 if ('' === $line && !$shortDescriptionCompleted) {
353 if ($shortDescription) {
354 $shortDescriptionCompleted = true;
355 }
356
357 continue;
358 }
359
360 if (!$shortDescriptionCompleted) {
361 $shortDescription = \sprintf("%s\n%s", $shortDescription, $line);
362
363 continue;
364 }
365
366 $longDescription = \sprintf("%s\n%s", $longDescription, $line);
367 }
368 }
369 }
370
371 $shortDescription = trim(preg_replace('/^#@[+-]{1}/m', '', $shortDescription), "\n");
372 $longDescription = trim($longDescription, "\n");
373
374 return [
375 $shortDescription ?: null,
376 $longDescription ?: null,
377 ];
378 }
379
380 private function getShortDescriptionFromDocNode(PhpDocNode $docNode, string $property): ?string
381 {
382 if ($shortDescription = $this->getDescriptionsFromDocNode($docNode)[0]) {
383 return $shortDescription;
384 }
385
386 foreach ($docNode->getVarTagValues() as $var) {
387 if (!$var->description) {
388 continue;
389 }
390
391 if (null !== $var->variableName && '' !== $var->variableName && '$'.$property !== $var->variableName) {
392 continue;
393 }
394
395 return $var->description;
396 }
397
398 foreach ($docNode->getTagsByName('@param') as $tagNode) {
399 if (!$tagNode instanceof PhpDocTagNode || !$tagNode->value instanceof ParamTagValueNode) {
400 continue;
401 }
402
403 if ('$'.$property !== $tagNode->value->parameterName) {
404 continue;
405 }
406
407 if ($tagNode->value->description) {
408 return $tagNode->value->description;
409 }
410 }
411
412 return null;
413 }
414
415 private function getDocBlockFromConstructor(string &$class, string $property): ?ParamTagValueNode
416 {
417 try {
418 $reflectionClass = new \ReflectionClass($class);
419 } catch (\ReflectionException) {
420 return null;
421 }
422
423 if (null === $reflectionConstructor = $reflectionClass->getConstructor()) {
424 return null;
425 }
426
427 if (!$rawDocNode = $reflectionConstructor->getDocComment()) {
428 return null;
429 }
430 $class = $reflectionConstructor->class;
431
432 $phpDocNode = $this->getPhpDocNode($rawDocNode);
433
434 return $this->filterDocBlockParams($phpDocNode, $property);
435 }
436
437 private function filterDocBlockParams(PhpDocNode $docNode, string $allowedParam): ?ParamTagValueNode
438 {
439 $tags = array_values(array_filter($docNode->getTagsByName('@param'), fn ($tagNode) => $tagNode instanceof PhpDocTagNode && ('$'.$allowedParam) === $tagNode->value->parameterName));
440
441 if (!$tags) {
442 return null;
443 }
444
445 return $tags[0]->value;
446 }
447
448 /**
449 * @return array{PhpDocNode|null, int|null, string|null, string|null}
450 */
451 private function getDocBlock(string $class, string $property): array
452 {
453 $propertyHash = $class.'::'.$property;
454
455 if (isset($this->docBlocks[$propertyHash])) {
456 return $this->docBlocks[$propertyHash];
457 }
458
459 $ucFirstProperty = ucfirst($property);
460
461 if ([$docBlock, $constructorDocBlock, $source, $declaringClass] = $this->getDocBlockFromProperty($class, $property)) {
462 if (!$docBlock?->getTagsByName('@var') && $constructorDocBlock) {
463 $docBlock = $constructorDocBlock;
464 }
465
466 $data = [$docBlock, $source, null, $declaringClass];
467 } elseif ([$docBlock, $_, $declaringClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR)) {
468 $data = [$docBlock, self::ACCESSOR, null, $declaringClass];
469 } elseif ([$docBlock, $prefix, $declaringClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR)) {
470 $data = [$docBlock, self::MUTATOR, $prefix, $declaringClass];
471 } else {
472 $data = [null, null, null, null];
473 }
474
475 return $this->docBlocks[$propertyHash] = $data;
476 }
477
478 /**
479 * @return array{?PhpDocNode, ?PhpDocNode, int, string}|null
480 */
481 private function getDocBlockFromProperty(string $class, string $property): ?array
482 {
483 // Use a ReflectionProperty instead of $class to get the parent class if applicable
484 try {
485 $reflectionProperty = new \ReflectionProperty($class, $property);
486 } catch (\ReflectionException) {
487 return null;
488 }
489
490 if (!$this->canAccessMemberBasedOnItsVisibility($reflectionProperty)) {
491 return null;
492 }
493
494 $reflector = $reflectionProperty->getDeclaringClass();
495
496 foreach ($reflector->getTraits() as $trait) {
497 if ($trait->hasProperty($property)) {
498 return $this->getDocBlockFromProperty($trait->getName(), $property);
499 }
500 }
501
502 $rawDocNode = $reflectionProperty->getDocComment();
503 $phpDocNode = $rawDocNode ? $this->getPhpDocNode($rawDocNode) : null;
504
505 $constructorPhpDocNode = null;
506 if ($reflectionProperty->isPromoted()) {
507 $constructorRawDocNode = (new \ReflectionMethod($class, '__construct'))->getDocComment();
508 $constructorPhpDocNode = $constructorRawDocNode ? $this->getPhpDocNode($constructorRawDocNode) : null;
509 }
510
511 $source = self::PROPERTY;
512 if (!$phpDocNode?->getTagsByName('@var') && $constructorPhpDocNode) {
513 $source = self::MUTATOR;
514 }
515
516 if (!$phpDocNode && !$constructorPhpDocNode) {
517 return null;
518 }
519
520 return [$phpDocNode, $constructorPhpDocNode, $source, $reflectionProperty->class];
521 }
522
523 /**
524 * @return array{PhpDocNode, string, string}|null
525 */
526 private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type): ?array
527 {
528 $prefixes = self::ACCESSOR === $type ? $this->accessorPrefixes : $this->mutatorPrefixes;
529 $prefix = null;
530 $method = null;
531
532 foreach ($prefixes as $prefix) {
533 $methodName = $prefix.$ucFirstProperty;
534
535 try {
536 $method = new \ReflectionMethod($class, $methodName);
537 if ($method->isStatic()) {
538 continue;
539 }
540
541 if (self::ACCESSOR === $type && \in_array((string) $method->getReturnType(), ['void', 'never'], true)) {
542 continue;
543 }
544
545 if (
546 (
547 (self::ACCESSOR === $type && !$method->getNumberOfRequiredParameters())
548 || (self::MUTATOR === $type && $method->getNumberOfParameters() >= 1)
549 )
550 && $this->canAccessMemberBasedOnItsVisibility($method)
551 ) {
552 break;
553 }
554 } catch (\ReflectionException) {
555 // Try the next prefix if the method doesn't exist
556 }
557 }
558
559 if (!$method) {
560 return null;
561 }
562
563 if (null === $rawDocNode = $method->getDocComment() ?: null) {
564 return null;
565 }
566
567 $phpDocNode = $this->getPhpDocNode($rawDocNode);
568
569 return [$phpDocNode, $prefix, $method->class];
570 }
571
572 private function getPhpDocNode(string $rawDocNode): PhpDocNode
573 {
574 $tokens = new TokenIterator($this->lexer->tokenize($rawDocNode));
575 $phpDocNode = $this->phpDocParser->parse($tokens);
576 $tokens->consumeTokenType(Lexer::TOKEN_END);
577
578 return $phpDocNode;
579 }
580
581 private function canAccessMemberBasedOnItsVisibility(\ReflectionProperty|\ReflectionMethod $member): bool
582 {
583 return $this->allowPrivateAccess || $member->isPublic();
584 }
585 }