Debian Codegraph @

lib/3rdParty/composer/symfony/property-info/Extractor/PhpDocExtractor.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\DocBlock;
15 use phpDocumentor\Reflection\DocBlock\Tags\InvalidTag;
16 use phpDocumentor\Reflection\DocBlockFactory;
17 use phpDocumentor\Reflection\DocBlockFactoryInterface;
18 use phpDocumentor\Reflection\Types\Context;
19 use phpDocumentor\Reflection\Types\ContextFactory;
20 use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface;
21 use Symfony\Component\PropertyInfo\PropertyDocBlockExtractorInterface;
22 use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
23 use Symfony\Component\PropertyInfo\Type as LegacyType;
24 use Symfony\Component\PropertyInfo\Util\PhpDocTypeHelper;
25 use Symfony\Component\TypeInfo\Exception\LogicException;
26 use Symfony\Component\TypeInfo\Type;
27 use Symfony\Component\TypeInfo\Type\ObjectType;
28 use Symfony\Component\TypeInfo\TypeContext\TypeContextFactory;
29
30 /**
31 * Extracts data using a PHPDoc parser.
32 *
33 * @author Kévin Dunglas <[email protected]>
34 *
35 * @final
36 */
37 class PhpDocExtractor implements PropertyDescriptionExtractorInterface, PropertyTypeExtractorInterface, ConstructorArgumentTypeExtractorInterface, PropertyDocBlockExtractorInterface
38 {
39 public const PROPERTY = 0;
40 public const ACCESSOR = 1;
41 public const MUTATOR = 2;
42
43 /**
44 * @var array<string, array{DocBlock|null, int|null, string|null, string|null}>
45 */
46 private array $docBlocks = [];
47
48 /**
49 * @var array<string, array{DocBlock, string}|false>
50 */
51 private array $promotedPropertyDocBlocks = [];
52
53 /**
54 * @var Context[]
55 */
56 private array $contexts = [];
57
58 private DocBlockFactoryInterface $docBlockFactory;
59 private ContextFactory $contextFactory;
60 private TypeContextFactory $typeContextFactory;
61 private PhpDocTypeHelper $phpDocTypeHelper;
62 private array $mutatorPrefixes;
63 private array $accessorPrefixes;
64 private array $arrayMutatorPrefixes;
65
66 /**
67 * @param string[]|null $mutatorPrefixes
68 * @param string[]|null $accessorPrefixes
69 * @param string[]|null $arrayMutatorPrefixes
70 */
71 public function __construct(?DocBlockFactoryInterface $docBlockFactory = null, ?array $mutatorPrefixes = null, ?array $accessorPrefixes = null, ?array $arrayMutatorPrefixes = null)
72 {
73 if (!class_exists(DocBlockFactory::class)) {
74 throw new \LogicException(\sprintf('Unable to use the "%s" class as the "phpdocumentor/reflection-docblock" package is not installed. Try running composer require "phpdocumentor/reflection-docblock".', __CLASS__));
75 }
76
77 $this->docBlockFactory = $docBlockFactory ?: DocBlockFactory::createInstance();
78 $this->contextFactory = new ContextFactory();
79 $this->typeContextFactory = new TypeContextFactory();
80 $this->phpDocTypeHelper = new PhpDocTypeHelper();
81 $this->mutatorPrefixes = $mutatorPrefixes ?? ReflectionExtractor::$defaultMutatorPrefixes;
82 $this->accessorPrefixes = $accessorPrefixes ?? ReflectionExtractor::$defaultAccessorPrefixes;
83 $this->arrayMutatorPrefixes = $arrayMutatorPrefixes ?? ReflectionExtractor::$defaultArrayMutatorPrefixes;
84 }
85
86 public function getShortDescription(string $class, string $property, array $context = []): ?string
87 {
88 $docBlockData = $this->getPromotedPropertyDocBlockData($class, $property);
89 if ($docBlockData && $shortDescription = $this->getShortDescriptionFromDocBlock($docBlockData[0])) {
90 return $shortDescription;
91 }
92
93 [$docBlock] = $this->findDocBlock($class, $property);
94 if (!$docBlock) {
95 return null;
96 }
97
98 return $this->getShortDescriptionFromDocBlock($docBlock);
99 }
100
101 public function getLongDescription(string $class, string $property, array $context = []): ?string
102 {
103 $docBlockData = $this->getPromotedPropertyDocBlockData($class, $property);
104 if ($docBlockData && '' !== $contents = $docBlockData[0]->getDescription()->render()) {
105 return $contents;
106 }
107
108 [$docBlock] = $this->findDocBlock($class, $property);
109 if (!$docBlock) {
110 return null;
111 }
112
113 $contents = $docBlock->getDescription()->render();
114
115 return '' === $contents ? null : $contents;
116 }
117
118 /**
119 * @deprecated since Symfony 7.3, use "getType" instead
120 */
121 public function getTypes(string $class, string $property, array $context = []): ?array
122 {
123 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getType()" instead.', __METHOD__, self::class);
124
125 /** @var DocBlock $docBlock */
126 [$docBlock, $source, $prefix, $declaringClass] = $this->findDocBlock($class, $property);
127 if (!$docBlock) {
128 return null;
129 }
130
131 $tag = match ($source) {
132 self::PROPERTY => 'var',
133 self::ACCESSOR => 'return',
134 self::MUTATOR => 'param',
135 };
136
137 $parentClass = null;
138 $types = [];
139 /** @var DocBlock\Tags\Var_|DocBlock\Tags\Return_|DocBlock\Tags\Param $tag */
140 foreach ($docBlock->getTagsByName($tag) as $tag) {
141 if ($tag && !$tag instanceof InvalidTag && null !== $tag->getType()) {
142 foreach ($this->phpDocTypeHelper->getTypes($tag->getType()) as $type) {
143 switch ($type->getClassName()) {
144 case 'self':
145 $resolvedClass = $declaringClass ?? $class;
146 break;
147
148 case 'static':
149 $resolvedClass = $class;
150 break;
151
152 case 'parent':
153 if (false !== $resolvedClass = $parentClass ??= get_parent_class($declaringClass ?? $class)) {
154 break;
155 }
156 // no break
157
158 default:
159 $types[] = $type;
160 continue 2;
161 }
162
163 $types[] = new LegacyType(LegacyType::BUILTIN_TYPE_OBJECT, $type->isNullable(), $resolvedClass, $type->isCollection(), $type->getCollectionKeyTypes(), $type->getCollectionValueTypes());
164 }
165 }
166 }
167
168 if (!isset($types[0])) {
169 return null;
170 }
171
172 if (!\in_array($prefix, $this->arrayMutatorPrefixes, true)) {
173 return $types;
174 }
175
176 return [new LegacyType(LegacyType::BUILTIN_TYPE_ARRAY, false, null, true, new LegacyType(LegacyType::BUILTIN_TYPE_INT), $types[0])];
177 }
178
179 /**
180 * @deprecated since Symfony 7.3, use "getTypeFromConstructor" instead
181 */
182 public function getTypesFromConstructor(string $class, string $property): ?array
183 {
184 trigger_deprecation('symfony/property-info', '7.3', 'The "%s()" method is deprecated, use "%s::getTypeFromConstructor()" instead.', __METHOD__, self::class);
185
186 $docBlock = $this->getDocBlockFromConstructor($class, $property);
187
188 if (!$docBlock) {
189 return null;
190 }
191
192 $types = [];
193 /** @var DocBlock\Tags\Var_|DocBlock\Tags\Return_|DocBlock\Tags\Param $tag */
194 foreach ($docBlock->getTagsByName('param') as $tag) {
195 if ($tag && null !== $tag->getType()) {
196 $types[] = $this->phpDocTypeHelper->getTypes($tag->getType());
197 }
198 }
199
200 if (!isset($types[0]) || [] === $types[0]) {
201 return null;
202 }
203
204 return array_merge([], ...$types);
205 }
206
207 public function getType(string $class, string $property, array $context = []): ?Type
208 {
209 if ([$propertyDocBlock, $propertyDeclaringClass] = $this->getPromotedPropertyDocBlockData($class, $property)) {
210 if ($type = $this->getTypeFromDocBlock($propertyDocBlock, self::PROPERTY, $class, $propertyDeclaringClass, null)) {
211 return $type;
212 }
213 }
214
215 [$docBlock, $source, $prefix, $declaringClass] = $this->findDocBlock($class, $property);
216 if (!$docBlock) {
217 return null;
218 }
219
220 return $this->getTypeFromDocBlock($docBlock, $source, $class, $declaringClass, $prefix);
221 }
222
223 public function getTypeFromConstructor(string $class, string $property): ?Type
224 {
225 if (!$docBlock = $this->getDocBlockFromConstructor($class, $property)) {
226 return null;
227 }
228
229 $types = [];
230 /** @var DocBlock\Tags\Var_|DocBlock\Tags\Return_|DocBlock\Tags\Param $tag */
231 foreach ($docBlock->getTagsByName('param') as $tag) {
232 if ($tag instanceof InvalidTag || !$tagType = $tag->getType()) {
233 continue;
234 }
235
236 $types[] = $this->phpDocTypeHelper->getType($tagType);
237 }
238
239 return $types[0] ?? null;
240 }
241
242 public function getDocBlock(string $class, string $property): ?DocBlock
243 {
244 return $this->findDocBlock($class, $property)[0];
245 }
246
247 private function getDocBlockFromConstructor(string $class, string $property): ?DocBlock
248 {
249 try {
250 $reflectionClass = new \ReflectionClass($class);
251 } catch (\ReflectionException) {
252 return null;
253 }
254 if (!$reflectionConstructor = $reflectionClass->getConstructor()) {
255 return null;
256 }
257
258 try {
259 $docBlock = $this->docBlockFactory->create($reflectionConstructor, $this->contextFactory->createFromReflector($reflectionConstructor));
260
261 return $this->filterDocBlockParams($docBlock, $property);
262 } catch (\InvalidArgumentException) {
263 return null;
264 }
265 }
266
267 private function filterDocBlockParams(DocBlock $docBlock, string $allowedParam): DocBlock
268 {
269 $tags = array_values(array_filter($docBlock->getTagsByName('param'), static fn ($tag) => $tag instanceof DocBlock\Tags\Param && $allowedParam === $tag->getVariableName()));
270
271 return new DocBlock($docBlock->getSummary(), $docBlock->getDescription(), $tags, $docBlock->getContext(),
272 $docBlock->getLocation(), $docBlock->isTemplateStart(), $docBlock->isTemplateEnd());
273 }
274
275 /**
276 * @return array{DocBlock|null, int|null, string|null, string|null}
277 */
278 private function findDocBlock(string $class, string $property): array
279 {
280 $propertyHash = \sprintf('%s::%s', $class, $property);
281
282 if (isset($this->docBlocks[$propertyHash])) {
283 return $this->docBlocks[$propertyHash];
284 }
285
286 try {
287 $reflectionProperty = new \ReflectionProperty($class, $property);
288 } catch (\ReflectionException) {
289 $reflectionProperty = null;
290 }
291
292 $ucFirstProperty = ucfirst($property);
293
294 if ($reflectionProperty?->isPromoted() && $docBlock = $this->getDocBlockFromConstructor($reflectionProperty->class, $property)) {
295 $data = [$docBlock, self::MUTATOR, null, $reflectionProperty->class];
296 } elseif ([$docBlock, $declaringClass] = $this->getDocBlockFromProperty($class, $property)) {
297 $data = [$docBlock, self::PROPERTY, null, $declaringClass];
298 } else {
299 $data = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR)
300 ?? $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR)
301 ?? [null, null, null, null];
302 }
303
304 return $this->docBlocks[$propertyHash] = $data;
305 }
306
307 /**
308 * @return array{DocBlock, string}|null
309 */
310 private function getDocBlockFromProperty(string $class, string $property, ?string $originalClass = null): ?array
311 {
312 $originalClass ??= $class;
313
314 // Use a ReflectionProperty instead of $class to get the parent class if applicable
315 try {
316 $reflectionProperty = new \ReflectionProperty($class, $property);
317 } catch (\ReflectionException) {
318 return null;
319 }
320
321 $reflector = $reflectionProperty->getDeclaringClass();
322
323 foreach ($reflector->getTraits() as $trait) {
324 if ($trait->hasProperty($property)) {
325 return $this->getDocBlockFromProperty($trait->getName(), $property, $reflector->isTrait() ? $originalClass : $reflector->getName());
326 }
327 }
328
329 $context = $this->createFromReflector($reflector);
330
331 try {
332 $declaringClass = $reflector->isTrait() ? $originalClass : $reflector->getName();
333
334 return [$this->docBlockFactory->create($reflectionProperty, $context), $declaringClass];
335 } catch (\InvalidArgumentException) {
336 return null;
337 } catch (\RuntimeException) {
338 // Workaround for phpdocumentor/reflection-docblock < 6 not supporting ?Type<...> syntax
339 if (($rawDoc = $reflectionProperty->getDocComment()) && $docBlock = $this->getNullableGenericDocBlock($rawDoc, $context)) {
340 return [$docBlock, $declaringClass ?? ($reflector->isTrait() ? $originalClass : $reflector->getName())];
341 }
342
343 return null;
344 }
345 }
346
347 /**
348 * @return array{DocBlock, int, ?string, string}|null
349 */
350 private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type, ?string $originalClass = null): ?array
351 {
352 $originalClass ??= $class;
353 $prefixes = self::ACCESSOR === $type ? $this->accessorPrefixes : $this->mutatorPrefixes;
354 $prefix = null;
355 $method = null;
356
357 foreach ($prefixes as $prefix) {
358 $methodName = $prefix.$ucFirstProperty;
359
360 try {
361 $method = new \ReflectionMethod($class, $methodName);
362 if ($method->isStatic()) {
363 continue;
364 }
365
366 if (self::ACCESSOR === $type && \in_array((string) $method->getReturnType(), ['void', 'never'], true)) {
367 continue;
368 }
369
370 if (
371 (self::ACCESSOR === $type && !$method->getNumberOfRequiredParameters())
372 || (self::MUTATOR === $type && $method->getNumberOfParameters() >= 1)
373 ) {
374 break;
375 }
376 } catch (\ReflectionException) {
377 // Try the next prefix if the method doesn't exist
378 }
379 }
380
381 if (!$method) {
382 return null;
383 }
384
385 $reflector = $method->getDeclaringClass();
386
387 foreach ($reflector->getTraits() as $trait) {
388 if ($trait->hasMethod($methodName)) {
389 return $this->getDocBlockFromMethod($trait->getName(), $ucFirstProperty, $type, $reflector->isTrait() ? $originalClass : $reflector->getName());
390 }
391 }
392
393 $context = $this->createFromReflector($reflector);
394 $prefix = self::ACCESSOR === $type ? null : $prefix;
395
396 try {
397 $declaringClass = $reflector->isTrait() ? $originalClass : $reflector->getName();
398
399 return [$this->docBlockFactory->create($method, $context), $type, $prefix, $declaringClass];
400 } catch (\InvalidArgumentException) {
401 return null;
402 } catch (\RuntimeException) {
403 // Workaround for phpdocumentor/reflection-docblock < 6 not supporting ?Type<...> syntax
404 if (($rawDoc = $method->getDocComment()) && $docBlock = $this->getNullableGenericDocBlock($rawDoc, $context)) {
405 return [$docBlock, $type, $prefix, $declaringClass ?? ($reflector->isTrait() ? $originalClass : $reflector->getName())];
406 }
407
408 return null;
409 }
410 }
411
412 private function getNullableGenericDocBlock(string $rawDoc, Context $context): ?DocBlock
413 {
414 // Converts "?Type<...>" to "Type<...>|null"
415 if ($rawDoc === $processedDoc = preg_replace('/@(var|param|return)\s+\?(\S+)/', '@$1 $2|null', $rawDoc)) {
416 return null;
417 }
418
419 try {
420 return $this->docBlockFactory->create($processedDoc, $context);
421 } catch (\InvalidArgumentException|\RuntimeException) {
422 return null;
423 }
424 }
425
426 /**
427 * Prevents a lot of redundant calls to ContextFactory::createForNamespace().
428 */
429 private function createFromReflector(\ReflectionClass $reflector): Context
430 {
431 $cacheKey = $reflector->getNamespaceName().':'.$reflector->getFileName();
432
433 return $this->contexts[$cacheKey] ??= $this->contextFactory->createFromReflector($reflector);
434 }
435
436 /**
437 * @return array{DocBlock, string}|null
438 */
439 private function getPromotedPropertyDocBlockData(string $class, string $property): ?array
440 {
441 $propertyHash = $class.'::'.$property;
442
443 if (isset($this->promotedPropertyDocBlocks[$propertyHash])) {
444 return false === $this->promotedPropertyDocBlocks[$propertyHash] ? null : $this->promotedPropertyDocBlocks[$propertyHash];
445 }
446
447 try {
448 $reflectionProperty = new \ReflectionProperty($class, $property);
449 } catch (\ReflectionException) {
450 $this->promotedPropertyDocBlocks[$propertyHash] = false;
451
452 return null;
453 }
454
455 if (!$reflectionProperty->isPromoted() || !$data = $this->getDocBlockFromProperty($class, $property)) {
456 $this->promotedPropertyDocBlocks[$propertyHash] = false;
457
458 return null;
459 }
460
461 return $this->promotedPropertyDocBlocks[$propertyHash] = $data;
462 }
463
464 private function getTypeFromDocBlock(DocBlock $docBlock, int $source, string $class, ?string $declaringClass, ?string $prefix): ?Type
465 {
466 $tag = match ($source) {
467 self::PROPERTY => 'var',
468 self::ACCESSOR => 'return',
469 self::MUTATOR => 'param',
470 };
471
472 $types = [];
473 $typeContext = $this->typeContextFactory->createFromClassName($class, $declaringClass ?? $class);
474
475 /** @var DocBlock\Tags\Var_|DocBlock\Tags\Return_|DocBlock\Tags\Param $tag */
476 foreach ($docBlock->getTagsByName($tag) as $tag) {
477 if ($tag instanceof InvalidTag || !$tagType = $tag->getType()) {
478 continue;
479 }
480
481 $type = $this->phpDocTypeHelper->getType($tagType);
482
483 if (!$type instanceof ObjectType) {
484 $types[] = $type;
485
486 continue;
487 }
488
489 $normalizedClassName = match ($type->getClassName()) {
490 'self' => $typeContext->getDeclaringClass(),
491 'static' => $typeContext->getCalledClass(),
492 default => $type->getClassName(),
493 };
494
495 if ('parent' === $normalizedClassName) {
496 try {
497 $normalizedClassName = $typeContext->getParentClass();
498 } catch (LogicException) {
499 // if there is no parent for the current class, we keep the "parent" raw string
500 }
501 }
502
503 $types[] = $type->isNullable() ? Type::nullable(Type::object($normalizedClassName)) : Type::object($normalizedClassName);
504 }
505
506 if (!$type = $types[0] ?? null) {
507 return null;
508 }
509
510 if (self::MUTATOR !== $source || !\in_array($prefix, $this->arrayMutatorPrefixes, true)) {
511 return $type;
512 }
513
514 return Type::list($type);
515 }
516
517 private function getShortDescriptionFromDocBlock(DocBlock $docBlock): ?string
518 {
519 if ($shortDescription = $docBlock->getSummary()) {
520 return $shortDescription;
521 }
522
523 foreach ($docBlock->getTagsByName('var') as $var) {
524 if ($var && !$var instanceof InvalidTag && $varDescription = $var->getDescription()->render()) {
525 return $varDescription;
526 }
527 }
528
529 foreach ($docBlock->getTagsByName('param') as $param) {
530 if (!$param instanceof DocBlock\Tags\Param) {
531 continue;
532 }
533
534 if ($paramDescription = $param->getDescription()?->render()) {
535 return $paramDescription;
536 }
537 }
538
539 return null;
540 }
541 }