1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Reflection;
4:
5: use Attribute;
6: use Closure;
7: use PhpParser\Node\Arg;
8: use PhpParser\Node\Expr\StaticCall;
9: use PhpParser\Node\Identifier;
10: use PhpParser\Node\Name\FullyQualified;
11: use PHPStan\Analyser\ArgumentsNormalizer;
12: use PHPStan\Analyser\OutOfClassScope;
13: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass;
14: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClassConstant;
15: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum;
16: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnumBackedCase;
17: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionMethod;
18: use PHPStan\BetterReflection\Reflection\Exception\CircularReference;
19: use PHPStan\DependencyInjection\GenerateFactory;
20: use PHPStan\DependencyInjection\Reflection\ClassReflectionExtensionRegistryProvider;
21: use PHPStan\Php\PhpVersion;
22: use PHPStan\PhpDoc\PhpDocInheritanceResolver;
23: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
24: use PHPStan\PhpDoc\StubPhpDocProvider;
25: use PHPStan\PhpDoc\Tag\ExtendsTag;
26: use PHPStan\PhpDoc\Tag\ImplementsTag;
27: use PHPStan\PhpDoc\Tag\MethodTag;
28: use PHPStan\PhpDoc\Tag\MixinTag;
29: use PHPStan\PhpDoc\Tag\PropertyTag;
30: use PHPStan\PhpDoc\Tag\RequireExtendsTag;
31: use PHPStan\PhpDoc\Tag\RequireImplementsTag;
32: use PHPStan\PhpDoc\Tag\SealedTypeTag;
33: use PHPStan\PhpDoc\Tag\TemplateTag;
34: use PHPStan\PhpDoc\Tag\TypeAliasImportTag;
35: use PHPStan\PhpDoc\Tag\TypeAliasTag;
36: use PHPStan\Reflection\Deprecation\DeprecationProvider;
37: use PHPStan\Reflection\Php\PhpPropertyReflection;
38: use PHPStan\Reflection\Php\UniversalObjectCratesClassReflectionExtension;
39: use PHPStan\Reflection\SignatureMap\SignatureMapProvider;
40: use PHPStan\ShouldNotHappenException;
41: use PHPStan\Turbo\ShadowedByTurboExtension;
42: use PHPStan\Type\CircularTypeAliasDefinitionException;
43: use PHPStan\Type\Constant\ConstantIntegerType;
44: use PHPStan\Type\ErrorType;
45: use PHPStan\Type\FileTypeMapper;
46: use PHPStan\Type\Generic\GenericObjectType;
47: use PHPStan\Type\Generic\TemplateType;
48: use PHPStan\Type\Generic\TemplateTypeFactory;
49: use PHPStan\Type\Generic\TemplateTypeHelper;
50: use PHPStan\Type\Generic\TemplateTypeMap;
51: use PHPStan\Type\Generic\TemplateTypeScope;
52: use PHPStan\Type\Generic\TemplateTypeVariance;
53: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
54: use PHPStan\Type\Generic\TypeProjectionHelper;
55: use PHPStan\Type\MixedType;
56: use PHPStan\Type\ObjectType;
57: use PHPStan\Type\Type;
58: use PHPStan\Type\TypeAlias;
59: use PHPStan\Type\TypehintHelper;
60: use PHPStan\Type\TypeTraverser;
61: use PHPStan\Type\VerbosityLevel;
62: use ReflectionClass as CoreReflectionClass;
63: use ReflectionException;
64: use function array_diff;
65: use function array_filter;
66: use function array_key_exists;
67: use function array_map;
68: use function array_merge;
69: use function array_pop;
70: use function array_shift;
71: use function array_unique;
72: use function array_values;
73: use function count;
74: use function implode;
75: use function in_array;
76: use function is_bool;
77: use function is_file;
78: use function is_int;
79: use function sprintf;
80: use function strtolower;
81:
82: /**
83: * @api
84: */
85: #[GenerateFactory(interface: ClassReflectionFactory::class)]
86: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ClassReflection.cpp')]
87: final class ClassReflection
88: {
89:
90: /** @var ExtendedMethodReflection[] */
91: private array $methods = [];
92:
93: /** @var ExtendedPropertyReflection[] */
94: private array $properties = [];
95:
96: /** @var ExtendedPropertyReflection[] */
97: private array $instanceProperties = [];
98:
99: /** @var ExtendedPropertyReflection[] */
100: private array $staticProperties = [];
101:
102: /** @var RealClassClassConstantReflection[] */
103: private array $constants = [];
104:
105: /** @var EnumCaseReflection[]|null */
106: private ?array $enumCases = null;
107:
108: /** @var int[]|null */
109: private ?array $classHierarchyDistances = null;
110:
111: private ?string $deprecatedDescription = null;
112:
113: private ?bool $isDeprecated = null;
114:
115: /** @var array<Type>|null */
116: private ?array $allowedSubTypes = null;
117:
118: private bool $allowedSubTypesResolved = false;
119:
120: private ?bool $isGeneric = null;
121:
122: private ?bool $isInternal = null;
123:
124: private ?bool $isFinal = null;
125:
126: private ?bool $isImmutable = null;
127:
128: private ?bool $hasConsistentConstructor = null;
129:
130: private ?bool $acceptsNamedArguments = null;
131:
132: private ?TemplateTypeMap $templateTypeMap = null;
133:
134: private ?TemplateTypeMap $activeTemplateTypeMap = null;
135:
136: private ?TemplateTypeVarianceMap $defaultCallSiteVarianceMap = null;
137:
138: private ?TemplateTypeVarianceMap $callSiteVarianceMap = null;
139:
140: /** @var array<string,ClassReflection>|null */
141: private ?array $ancestors = null;
142:
143: private ?string $cacheKey = null;
144:
145: /** @var array<string, bool> */
146: private array $subclasses = [];
147:
148: private string|false|null $filename = false;
149:
150: private string|false|null $reflectionDocComment = false;
151:
152: private false|ResolvedPhpDocBlock|null $stubPhpDocBlock = false;
153:
154: private false|ResolvedPhpDocBlock $resolvedPhpDocBlock = false;
155:
156: private false|ResolvedPhpDocBlock $traitContextResolvedPhpDocBlock = false;
157:
158: /** @var array<string, ClassReflection>|null */
159: private ?array $cachedInterfaces = null;
160:
161: private ClassReflection|false|null $cachedParentClass = false;
162:
163: /**
164: * Name of the class the parent class chain loops back to, false when it has not been looked for yet.
165: *
166: * @var class-string|false|null
167: */
168: private string|false|null $circularParentClassName = false;
169:
170: /** @var array<string, TypeAlias>|null */
171: private ?array $typeAliases = null;
172:
173: /** @var array<string, true> */
174: private static array $resolvingTypeAliasImports = [];
175:
176: /** @var array<string, bool> */
177: private array $hasMethodCache = [];
178:
179: /** @var array<string, bool> */
180: private array $hasPropertyCache = [];
181:
182: /** @var array<string, bool> */
183: private array $hasInstancePropertyCache = [];
184:
185: /** @var array<string, bool> */
186: private array $hasStaticPropertyCache = [];
187:
188: /**
189: * getName() is the hottest call on this class (millions per run), two adapter frames deep
190: *
191: * @var class-string|null
192: */
193: private ?string $name = null;
194:
195: /**
196: * @param ReflectionClass|ReflectionEnum $reflection
197: * @param (Closure(): ?ResolvedPhpDocBlock)|null $stubPhpDocBlockCallback
198: */
199: public function __construct(
200: private ClassReflectionFactory $classReflectionFactory,
201: private ReflectionProvider $reflectionProvider,
202: private InitializerExprTypeResolver $initializerExprTypeResolver,
203: private FileTypeMapper $fileTypeMapper,
204: private StubPhpDocProvider $stubPhpDocProvider,
205: private PhpDocInheritanceResolver $phpDocInheritanceResolver,
206: private PhpVersion $phpVersion,
207: private SignatureMapProvider $signatureMapProvider,
208: private DeprecationProvider $deprecationProvider,
209: private AttributeReflectionFactory $attributeReflectionFactory,
210: private ClassReflectionExtensionRegistryProvider $classReflectionExtensionRegistryProvider,
211: private string $displayName,
212: private CoreReflectionClass $reflection,
213: private ?string $anonymousFilename,
214: private ?TemplateTypeMap $resolvedTemplateTypeMap,
215: private ?Closure $stubPhpDocBlockCallback,
216: private ?string $extraCacheKey = null,
217: private ?TemplateTypeVarianceMap $resolvedCallSiteVarianceMap = null,
218: private ?bool $finalByKeywordOverride = null,
219: )
220: {
221: }
222:
223: public function getNativeReflection(): ReflectionClass|ReflectionEnum
224: {
225: return $this->reflection;
226: }
227:
228: public function getFileName(): ?string
229: {
230: if (!is_bool($this->filename)) {
231: return $this->filename;
232: }
233:
234: if ($this->anonymousFilename !== null) {
235: return $this->filename = $this->anonymousFilename;
236: }
237: $fileName = $this->reflection->getFileName();
238: if ($fileName === false) {
239: return $this->filename = null;
240: }
241:
242: if (!is_file($fileName)) {
243: return $this->filename = null;
244: }
245:
246: return $this->filename = $fileName;
247: }
248:
249: public function getParentClass(): ?ClassReflection
250: {
251: if (!is_bool($this->cachedParentClass)) {
252: return $this->cachedParentClass;
253: }
254:
255: $parentClass = $this->reflection->getParentClass();
256:
257: if ($parentClass === false) {
258: return $this->cachedParentClass = null;
259: }
260:
261: $circularParentClassName = $this->findCircularParentClassName($parentClass->getName());
262: if ($circularParentClassName !== null) {
263: throw CircularReference::fromClassName($circularParentClassName);
264: }
265:
266: $extendsTag = $this->getFirstExtendsTag();
267:
268: if ($extendsTag !== null && $this->isValidAncestorType($extendsTag->getType(), [$parentClass->getName()])) {
269: $extendedType = $extendsTag->getType();
270:
271: if ($this->isGeneric()) {
272: $extendedType = TemplateTypeHelper::resolveTemplateTypes(
273: $extendedType,
274: $this->getActiveTemplateTypeMapForAncestorResolution(),
275: $this->getCallSiteVarianceMap(),
276: TemplateTypeVariance::createStatic(),
277: );
278: }
279:
280: // a generic parent is a new reflection, remembered so that walking up a generic
281: // hierarchy does not resolve each ancestor again from every class below it
282: if (!$extendedType instanceof GenericObjectType) {
283: return $this->cachedParentClass = $this->reflectionProvider->getClass($parentClass->getName());
284: }
285:
286: return $this->cachedParentClass = $extendedType->getClassReflection() ?? $this->reflectionProvider->getClass($parentClass->getName());
287: }
288:
289: $parentReflection = $this->reflectionProvider->getClass($parentClass->getName());
290: if ($parentReflection->isGeneric()) {
291: return $this->cachedParentClass = $parentReflection->withTypes(
292: array_values($parentReflection->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()),
293: );
294: }
295:
296: $this->cachedParentClass = $parentReflection;
297:
298: return $parentReflection;
299: }
300:
301: /**
302: * BetterReflection only rejects a class extending itself directly. A cycle spanning
303: * several classes (A extends B, B extends A) reaches this class intact and would make
304: * every walk over the class hierarchy run forever, so it is detected here instead.
305: *
306: * @param class-string $parentClassName
307: * @return class-string|null Name of the class the chain loops back to
308: */
309: private function findCircularParentClassName(string $parentClassName): ?string
310: {
311: if (!is_bool($this->circularParentClassName)) {
312: return $this->circularParentClassName;
313: }
314:
315: $this->circularParentClassName = null;
316:
317: $visitedClassNames = [strtolower($this->getName()) => true];
318: $currentClassName = $parentClassName;
319:
320: while (true) {
321: $lowercasedClassName = strtolower($currentClassName);
322: if (array_key_exists($lowercasedClassName, $visitedClassNames)) {
323: return $this->circularParentClassName = $currentClassName;
324: }
325:
326: $visitedClassNames[$lowercasedClassName] = true;
327:
328: if (!$this->reflectionProvider->hasClass($currentClassName)) {
329: return null;
330: }
331:
332: $parentClass = $this->reflectionProvider->getClass($currentClassName)->reflection->getParentClass();
333: if ($parentClass === false) {
334: return null;
335: }
336:
337: $currentClassName = $parentClass->getName();
338: }
339: }
340:
341: /**
342: * @return class-string
343: */
344: public function getName(): string
345: {
346: return $this->name ??= $this->reflection->getName();
347: }
348:
349: public function getDisplayName(bool $withTemplateTypes = true): string
350: {
351: if (
352: $withTemplateTypes === false
353: || $this->resolvedTemplateTypeMap === null
354: || count($this->resolvedTemplateTypeMap->getTypes()) === 0
355: ) {
356: return $this->displayName;
357: }
358:
359: $templateTypes = [];
360: $variances = $this->getCallSiteVarianceMap()->getVariances();
361: foreach ($this->getActiveTemplateTypeMap()->getTypes() as $name => $templateType) {
362: $variance = $variances[$name] ?? null;
363: if ($variance === null) {
364: continue;
365: }
366:
367: $templateTypes[] = TypeProjectionHelper::describe($templateType, $variance, VerbosityLevel::typeOnly());
368: }
369:
370: return $this->displayName . '<' . implode(',', $templateTypes) . '>';
371: }
372:
373: public function getCacheKey(): string
374: {
375: $cacheKey = $this->cacheKey;
376: if ($cacheKey !== null) {
377: return $this->cacheKey;
378: }
379:
380: $cacheKey = $this->displayName;
381:
382: if ($this->resolvedTemplateTypeMap !== null) {
383: $templateTypes = [];
384: $variances = $this->getCallSiteVarianceMap()->getVariances();
385: foreach ($this->getActiveTemplateTypeMap()->getTypes() as $name => $templateType) {
386: $variance = $variances[$name] ?? null;
387: if ($variance === null) {
388: continue;
389: }
390:
391: $templateTypes[] = TypeProjectionHelper::describe($templateType, $variance, VerbosityLevel::cache());
392: }
393:
394: $cacheKey .= '<' . implode(',', $templateTypes) . '>';
395: }
396:
397: if ($this->hasFinalByKeywordOverride()) {
398: $cacheKey .= '-f=' . ($this->isFinalByKeyword() ? 't' : 'f');
399: }
400:
401: if ($this->extraCacheKey !== null) {
402: $cacheKey .= '-' . $this->extraCacheKey;
403: }
404:
405: $this->cacheKey = $cacheKey;
406:
407: return $cacheKey;
408: }
409:
410: /**
411: * @return int[]
412: */
413: public function getClassHierarchyDistances(): array
414: {
415: if ($this->classHierarchyDistances === null) {
416: $distance = 0;
417: $distances = [
418: $this->getName() => $distance,
419: ];
420: $currentClassReflection = $this;
421: foreach ($this->collectTraits($this->getNativeReflection()) as $trait) {
422: $distance++;
423: if (array_key_exists($trait->getName(), $distances)) {
424: continue;
425: }
426:
427: $distances[$trait->getName()] = $distance;
428: }
429:
430: // walking the parents through getParentClass() and not through the native
431: // reflection makes a cyclic class hierarchy end in a CircularReference
432: // exception instead of looping forever
433: while (($currentClassReflection = $currentClassReflection->getParentClass()) !== null) {
434: $distance++;
435: $parentClassName = $currentClassReflection->getName();
436: if (!array_key_exists($parentClassName, $distances)) {
437: $distances[$parentClassName] = $distance;
438: }
439: foreach ($this->collectTraits($currentClassReflection->getNativeReflection()) as $trait) {
440: $distance++;
441: if (array_key_exists($trait->getName(), $distances)) {
442: continue;
443: }
444:
445: $distances[$trait->getName()] = $distance;
446: }
447: }
448: foreach ($this->getNativeReflection()->getInterfaces() as $interface) {
449: $distance++;
450: if (array_key_exists($interface->getName(), $distances)) {
451: continue;
452: }
453:
454: $distances[$interface->getName()] = $distance;
455: }
456:
457: $this->classHierarchyDistances = $distances;
458: }
459:
460: return $this->classHierarchyDistances;
461: }
462:
463: /**
464: * @return list<ReflectionClass>
465: */
466: private function collectTraits(ReflectionClass|ReflectionEnum $class): array
467: {
468: $traits = [];
469: $traitsLeftToAnalyze = $class->getTraits();
470:
471: while (count($traitsLeftToAnalyze) !== 0) {
472: $trait = array_shift($traitsLeftToAnalyze);
473: // traits can use each other in a cycle - compare by name because
474: // the reflection objects are not guaranteed to be identical
475: if (array_key_exists($trait->getName(), $traits)) {
476: continue;
477: }
478:
479: $traits[$trait->getName()] = $trait;
480:
481: foreach ($trait->getTraits() as $subTrait) {
482: $traitsLeftToAnalyze[] = $subTrait;
483: }
484: }
485:
486: return array_values($traits);
487: }
488:
489: public function allowsDynamicProperties(): bool
490: {
491: if ($this->isEnum()) {
492: return false;
493: }
494:
495: if (!$this->phpVersion->deprecatesDynamicProperties()) {
496: return true;
497: }
498:
499: $hasMagicMethod = $this->hasNativeMethod('__get') || $this->hasNativeMethod('__set') || $this->hasNativeMethod('__isset');
500: if ($hasMagicMethod) {
501: return true;
502: }
503:
504: foreach ($this->getRequireExtendsTags() as $extendsTag) {
505: $type = $extendsTag->getType();
506: if (!$type instanceof ObjectType) {
507: continue;
508: }
509:
510: $reflection = $type->getClassReflection();
511: if ($reflection === null || !$reflection->allowsDynamicProperties()) {
512: continue;
513: }
514:
515: return true;
516: }
517:
518: if ($this->isReadOnly()) {
519: return false;
520: }
521:
522: if (UniversalObjectCratesClassReflectionExtension::isUniversalObjectCrate(
523: $this->reflectionProvider,
524: $this,
525: )) {
526: return true;
527: }
528:
529: $class = $this;
530: do {
531: $attributes = $class->reflection->getAttributes('AllowDynamicProperties');
532: $class = $class->getParentClass();
533: } while ($attributes === [] && $class !== null);
534:
535: return $attributes !== [];
536: }
537:
538: /**
539: * @deprecated Use hasInstanceProperty or hasStaticProperty instead
540: */
541: public function hasProperty(string $propertyName): bool
542: {
543: if (array_key_exists($propertyName, $this->hasPropertyCache)) {
544: return $this->hasPropertyCache[$propertyName];
545: }
546:
547: if ($this->isEnum()) {
548: return $this->hasPropertyCache[$propertyName] = $this->hasNativeProperty($propertyName);
549: }
550:
551: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->hasProperty($this, $propertyName)) {
552: return $this->hasPropertyCache[$propertyName] = true;
553: }
554:
555: if ($this->allowsDynamicProperties()) {
556: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPropertiesClassReflectionExtensions() as $extension) {
557: if ($extension->hasProperty($this, $propertyName)) {
558: return $this->hasPropertyCache[$propertyName] = true;
559: }
560: }
561: }
562:
563: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension()->hasProperty($this, $propertyName)) {
564: return $this->hasPropertyCache[$propertyName] = true;
565: }
566:
567: return $this->hasPropertyCache[$propertyName] = false;
568: }
569:
570: public function hasInstanceProperty(string $propertyName): bool
571: {
572: if (array_key_exists($propertyName, $this->hasInstancePropertyCache)) {
573: return $this->hasInstancePropertyCache[$propertyName];
574: }
575:
576: if ($this->isEnum()) {
577: return $this->hasInstancePropertyCache[$propertyName] = $this->hasNativeProperty($propertyName);
578: }
579:
580: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
581: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
582: $property = $phpClassReflectionExtension->getNativeProperty($this, $propertyName);
583: if (!$property->isStatic()) {
584: return $this->hasInstancePropertyCache[$propertyName] = true;
585: }
586: }
587:
588: if ($this->allowsDynamicProperties()) {
589: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPropertiesClassReflectionExtensions() as $extension) {
590: if ($extension->hasProperty($this, $propertyName)) {
591: $property = $extension->getProperty($this, $propertyName);
592: if ($property->isStatic()) {
593: continue;
594: }
595: return $this->hasInstancePropertyCache[$propertyName] = true;
596: }
597: }
598: }
599:
600: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension()->hasInstanceProperty($this, $propertyName)) {
601: return $this->hasInstancePropertyCache[$propertyName] = true;
602: }
603:
604: return $this->hasInstancePropertyCache[$propertyName] = false;
605: }
606:
607: public function hasStaticProperty(string $propertyName): bool
608: {
609: if (array_key_exists($propertyName, $this->hasStaticPropertyCache)) {
610: return $this->hasStaticPropertyCache[$propertyName];
611: }
612:
613: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
614: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
615: $property = $phpClassReflectionExtension->getNativeProperty($this, $propertyName);
616: if ($property->isStatic()) {
617: return $this->hasStaticPropertyCache[$propertyName] = true;
618: }
619: }
620:
621: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension()->hasStaticProperty($this, $propertyName)) {
622: return $this->hasStaticPropertyCache[$propertyName] = true;
623: }
624:
625: return $this->hasStaticPropertyCache[$propertyName] = false;
626: }
627:
628: public function hasMethod(string $methodName): bool
629: {
630: if (array_key_exists($methodName, $this->hasMethodCache)) {
631: return $this->hasMethodCache[$methodName];
632: }
633:
634: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->hasMethod($this, $methodName)) {
635: return $this->hasMethodCache[$methodName] = true;
636: }
637:
638: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getMethodsClassReflectionExtensions() as $extension) {
639: if ($extension->hasMethod($this, $methodName)) {
640: return $this->hasMethodCache[$methodName] = true;
641: }
642: }
643:
644: if ($this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsMethodsClassReflectionExtension()->hasMethod($this, $methodName)) {
645: return $this->hasMethodCache[$methodName] = true;
646: }
647:
648: return $this->hasMethodCache[$methodName] = false;
649: }
650:
651: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
652: {
653: $key = $methodName;
654: if ($scope->isInClass()) {
655: $key = sprintf('%s-%s', $key, $scope->getClassReflection()->getCacheKey());
656: }
657:
658: if (array_key_exists($key, $this->methods)) {
659: return $this->methods[$key];
660: }
661:
662: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
663: if ($phpClassReflectionExtension->hasMethod($this, $methodName)) {
664: $method = $phpClassReflectionExtension->getMethod($this, $methodName);
665: if ($scope->canCallMethod($method)) {
666: return $this->methods[$key] = $method;
667: }
668: $this->methods[$key] = $method;
669: }
670:
671: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getMethodsClassReflectionExtensions() as $extension) {
672: if (!$extension->hasMethod($this, $methodName)) {
673: continue;
674: }
675:
676: $method = $this->wrapExtendedMethod($extension->getMethod($this, $methodName));
677: if ($scope->canCallMethod($method)) {
678: return $this->methods[$key] = $method;
679: }
680: $this->methods[$key] = $method;
681: }
682:
683: if (!isset($this->methods[$key])) {
684: $requireExtendsMethodsClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsMethodsClassReflectionExtension();
685: if ($requireExtendsMethodsClassReflectionExtension->hasMethod($this, $methodName)) {
686: $method = $requireExtendsMethodsClassReflectionExtension->getMethod($this, $methodName);
687: $this->methods[$key] = $method;
688: }
689: }
690:
691: if (!isset($this->methods[$key])) {
692: throw new MissingMethodFromReflectionException($this->getName(), $methodName);
693: }
694:
695: return $this->methods[$key];
696: }
697:
698: private function wrapExtendedMethod(MethodReflection $method): ExtendedMethodReflection
699: {
700: if ($method instanceof ExtendedMethodReflection) {
701: return $method;
702: }
703:
704: return new WrappedExtendedMethodReflection($method);
705: }
706:
707: private function wrapExtendedProperty(string $propertyName, PropertyReflection $method): ExtendedPropertyReflection
708: {
709: if ($method instanceof ExtendedPropertyReflection) {
710: return $method;
711: }
712:
713: return new WrappedExtendedPropertyReflection($propertyName, $method);
714: }
715:
716: public function hasNativeMethod(string $methodName): bool
717: {
718: return $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->hasNativeMethod($this, $methodName);
719: }
720:
721: public function getNativeMethod(string $methodName): ExtendedMethodReflection
722: {
723: if (!$this->hasNativeMethod($methodName)) {
724: throw new MissingMethodFromReflectionException($this->getName(), $methodName);
725: }
726: return $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->getNativeMethod($this, $methodName);
727: }
728:
729: public function hasConstructor(): bool
730: {
731: return $this->findConstructor() !== null;
732: }
733:
734: public function getConstructor(): ExtendedMethodReflection
735: {
736: $constructor = $this->findConstructor();
737: if ($constructor === null) {
738: throw new ShouldNotHappenException();
739: }
740: return $this->getNativeMethod($constructor->getName());
741: }
742:
743: private function findConstructor(): ?ReflectionMethod
744: {
745: $constructor = $this->reflection->getConstructor();
746: if ($constructor === null) {
747: return null;
748: }
749:
750: if ($this->phpVersion->supportsLegacyConstructor()) {
751: return $constructor;
752: }
753:
754: if (strtolower($constructor->getName()) !== '__construct') {
755: return null;
756: }
757:
758: return $constructor;
759: }
760:
761: /** @internal */
762: public function evictPrivateSymbols(): void
763: {
764: foreach ($this->constants as $name => $constant) {
765: if (!$constant->isPrivate()) {
766: continue;
767: }
768:
769: unset($this->constants[$name]);
770: }
771: foreach ($this->properties as $name => $property) {
772: if (!$property->isPrivate()) {
773: continue;
774: }
775:
776: unset($this->properties[$name]);
777: }
778: foreach ($this->instanceProperties as $name => $property) {
779: if (!$property->isPrivate()) {
780: continue;
781: }
782:
783: unset($this->instanceProperties[$name]);
784: }
785: foreach ($this->staticProperties as $name => $property) {
786: if (!$property->isPrivate()) {
787: continue;
788: }
789:
790: unset($this->staticProperties[$name]);
791: }
792: foreach ($this->methods as $name => $method) {
793: if (!$method->isPrivate()) {
794: continue;
795: }
796:
797: unset($this->methods[$name]);
798: }
799: // PhpClassReflectionExtension's member caches are governed by their own LRU
800: // (see PhpClassReflectionExtension::touchMemberCacheKey()) instead of per-class
801: // private-symbol eviction.
802: }
803:
804: /** @deprecated Use getInstanceProperty or getStaticProperty */
805: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
806: {
807: if ($this->isEnum()) {
808: return $this->getNativeProperty($propertyName);
809: }
810:
811: $key = $propertyName;
812: if ($scope->isInClass()) {
813: $key = sprintf('%s-%s', $key, $scope->getClassReflection()->getCacheKey());
814: }
815:
816: if (array_key_exists($key, $this->properties)) {
817: return $this->properties[$key];
818: }
819:
820: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
821: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
822: $property = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->getProperty($this, $propertyName, $scope);
823: if ($scope->canReadProperty($property)) {
824: return $this->properties[$key] = $property;
825: }
826: $this->properties[$key] = $property;
827: }
828:
829: if ($this->allowsDynamicProperties()) {
830: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPropertiesClassReflectionExtensions() as $extension) {
831: if (!$extension->hasProperty($this, $propertyName)) {
832: continue;
833: }
834:
835: $property = $this->wrapExtendedProperty($propertyName, $extension->getProperty($this, $propertyName));
836: if ($scope->canReadProperty($property)) {
837: return $this->properties[$key] = $property;
838: }
839: $this->properties[$key] = $property;
840: }
841: }
842:
843: // For BC purpose
844: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
845: $property = $phpClassReflectionExtension->getProperty($this, $propertyName, $scope);
846:
847: return $this->properties[$key] = $property;
848: }
849:
850: if (!isset($this->properties[$key])) {
851: $requireExtendsPropertiesClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension();
852: if ($requireExtendsPropertiesClassReflectionExtension->hasProperty($this, $propertyName)) {
853: $property = $requireExtendsPropertiesClassReflectionExtension->getProperty($this, $propertyName);
854: $this->properties[$key] = $property;
855: }
856: }
857:
858: if (!isset($this->properties[$key])) {
859: throw new MissingPropertyFromReflectionException($this->getName(), $propertyName);
860: }
861:
862: return $this->properties[$key];
863: }
864:
865: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
866: {
867: if ($this->isEnum()) {
868: return $this->getNativeProperty($propertyName);
869: }
870:
871: $key = $propertyName;
872: if ($scope->isInClass()) {
873: $key = sprintf('%s-%s', $key, $scope->getClassReflection()->getCacheKey());
874: }
875:
876: if (!isset($this->instanceProperties[$key])) {
877: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
878: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
879: $property = $phpClassReflectionExtension->getProperty($this, $propertyName, $scope);
880: if (!$property->isStatic()) {
881: if ($scope->canReadProperty($property)) {
882: return $this->instanceProperties[$key] = $property;
883: }
884: $this->instanceProperties[$key] = $property;
885: }
886: }
887:
888: if ($this->allowsDynamicProperties()) {
889: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getPropertiesClassReflectionExtensions() as $extension) {
890: if (!$extension->hasProperty($this, $propertyName)) {
891: continue;
892: }
893:
894: $nakedProperty = $extension->getProperty($this, $propertyName);
895: if ($nakedProperty->isStatic()) {
896: continue;
897: }
898:
899: $property = $this->wrapExtendedProperty($propertyName, $nakedProperty);
900: if ($scope->canReadProperty($property)) {
901: return $this->instanceProperties[$key] = $property;
902: }
903: $this->instanceProperties[$key] = $property;
904: }
905: }
906: }
907:
908: if (!isset($this->instanceProperties[$key])) {
909: $requireExtendsPropertiesClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension();
910: if ($requireExtendsPropertiesClassReflectionExtension->hasInstanceProperty($this, $propertyName)) {
911: $property = $requireExtendsPropertiesClassReflectionExtension->getInstanceProperty($this, $propertyName);
912: $this->instanceProperties[$key] = $property;
913: }
914: }
915:
916: if (!isset($this->instanceProperties[$key])) {
917: throw new MissingPropertyFromReflectionException($this->getName(), $propertyName);
918: }
919:
920: return $this->instanceProperties[$key];
921: }
922:
923: public function getStaticProperty(string $propertyName): ExtendedPropertyReflection
924: {
925: $key = $propertyName;
926: if (isset($this->staticProperties[$key])) {
927: return $this->staticProperties[$key];
928: }
929:
930: $phpClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension();
931: if ($phpClassReflectionExtension->hasProperty($this, $propertyName)) {
932: $nakedProperty = $phpClassReflectionExtension->getProperty($this, $propertyName, new OutOfClassScope());
933: if ($nakedProperty->isStatic()) {
934: $property = $this->wrapExtendedProperty($propertyName, $nakedProperty);
935: if ($property->isStatic()) {
936: return $this->staticProperties[$key] = $property;
937: }
938: }
939: }
940:
941: $requireExtendsPropertiesClassReflectionExtension = $this->classReflectionExtensionRegistryProvider->getRegistry()->getRequireExtendsPropertyClassReflectionExtension();
942: if ($requireExtendsPropertiesClassReflectionExtension->hasStaticProperty($this, $propertyName)) {
943: $property = $requireExtendsPropertiesClassReflectionExtension->getStaticProperty($this, $propertyName);
944: return $this->staticProperties[$key] = $property;
945: }
946:
947: throw new MissingPropertyFromReflectionException($this->getName(), $propertyName);
948: }
949:
950: public function hasNativeProperty(string $propertyName): bool
951: {
952: return $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->hasProperty($this, $propertyName);
953: }
954:
955: public function getNativeProperty(string $propertyName): PhpPropertyReflection
956: {
957: if (!$this->hasNativeProperty($propertyName)) {
958: throw new MissingPropertyFromReflectionException($this->getName(), $propertyName);
959: }
960:
961: return $this->classReflectionExtensionRegistryProvider->getRegistry()->getPhpClassReflectionExtension()->getNativeProperty($this, $propertyName);
962: }
963:
964: public function isAbstract(): bool
965: {
966: return $this->reflection->isAbstract();
967: }
968:
969: public function isInterface(): bool
970: {
971: return $this->reflection->isInterface();
972: }
973:
974: public function isTrait(): bool
975: {
976: return $this->reflection->isTrait();
977: }
978:
979: /**
980: * @phpstan-assert-if-true ReflectionEnum $this->reflection
981: * @phpstan-assert-if-true ReflectionEnum $this->getNativeReflection()
982: */
983: public function isEnum(): bool
984: {
985: return $this->reflection instanceof ReflectionEnum && $this->reflection->isEnum();
986: }
987:
988: /**
989: * @return 'Interface'|'Trait'|'Enum'|'Class'
990: */
991: public function getClassTypeDescription(): string
992: {
993: if ($this->isInterface()) {
994: return 'Interface';
995: } elseif ($this->isTrait()) {
996: return 'Trait';
997: } elseif ($this->isEnum()) {
998: return 'Enum';
999: }
1000:
1001: return 'Class';
1002: }
1003:
1004: public function isReadOnly(): bool
1005: {
1006: return $this->reflection->isReadOnly();
1007: }
1008:
1009: public function isBackedEnum(): bool
1010: {
1011: if (!$this->reflection instanceof ReflectionEnum) {
1012: return false;
1013: }
1014:
1015: return $this->reflection->isBacked();
1016: }
1017:
1018: public function getBackedEnumType(): ?Type
1019: {
1020: if (!$this->reflection instanceof ReflectionEnum) {
1021: return null;
1022: }
1023:
1024: if (!$this->reflection->isBacked()) {
1025: return null;
1026: }
1027:
1028: return TypehintHelper::decideTypeFromReflection($this->reflection->getBackingType());
1029: }
1030:
1031: public function hasEnumCase(string $name): bool
1032: {
1033: if (!$this->isEnum()) {
1034: return false;
1035: }
1036:
1037: return $this->reflection->hasCase($name);
1038: }
1039:
1040: /**
1041: * @return array<string, EnumCaseReflection>
1042: */
1043: public function getEnumCases(): array
1044: {
1045: if (!$this->isEnum()) {
1046: throw new ShouldNotHappenException();
1047: }
1048:
1049: if ($this->enumCases !== null) {
1050: return $this->enumCases;
1051: }
1052:
1053: $cases = [];
1054: $initializerExprContext = InitializerExprContext::fromClassReflection($this);
1055: foreach ($this->reflection->getCases() as $case) {
1056: $valueType = null;
1057: if ($case instanceof ReflectionEnumBackedCase && $case->hasBackingValue()) {
1058: $valueType = $this->initializerExprTypeResolver->getEnumCaseValueType($this->getName(), $case->getName(), $case->getValueExpression(), $initializerExprContext);
1059: }
1060: $caseName = $case->getName();
1061: $attributes = $this->attributeReflectionFactory->fromNativeReflection($case->getAttributes(), InitializerExprContext::fromClass($this->getName(), $this->getFileName()));
1062: $cases[$caseName] = new EnumCaseReflection($this, $case, $valueType, $attributes, $this->deprecationProvider);
1063: }
1064:
1065: return $this->enumCases = $cases;
1066: }
1067:
1068: public function getEnumCase(string $name): EnumCaseReflection
1069: {
1070: if (!$this->hasEnumCase($name)) {
1071: throw new ShouldNotHappenException(sprintf('Enum case %s::%s does not exist.', $this->getDisplayName(), $name));
1072: }
1073:
1074: if (!$this->reflection instanceof ReflectionEnum) {
1075: throw new ShouldNotHappenException();
1076: }
1077:
1078: if ($this->enumCases !== null && array_key_exists($name, $this->enumCases)) {
1079: return $this->enumCases[$name];
1080: }
1081:
1082: $case = $this->reflection->getCase($name);
1083: $valueType = null;
1084: if ($case instanceof ReflectionEnumBackedCase && $case->hasBackingValue()) {
1085: $valueType = $this->initializerExprTypeResolver->getEnumCaseValueType($this->getName(), $name, $case->getValueExpression(), InitializerExprContext::fromClassReflection($this));
1086: }
1087:
1088: $attributes = $this->attributeReflectionFactory->fromNativeReflection($case->getAttributes(), InitializerExprContext::fromClass($this->getName(), $this->getFileName()));
1089:
1090: return new EnumCaseReflection($this, $case, $valueType, $attributes, $this->deprecationProvider);
1091: }
1092:
1093: public function isClass(): bool
1094: {
1095: return !$this->isInterface() && !$this->isTrait() && !$this->isEnum();
1096: }
1097:
1098: public function isAnonymous(): bool
1099: {
1100: return $this->anonymousFilename !== null;
1101: }
1102:
1103: public function is(string $className): bool
1104: {
1105: if ($this->getName() === $className) {
1106: return true;
1107: }
1108:
1109: if (!$this->reflectionProvider->hasClass($className)) {
1110: return false;
1111: }
1112:
1113: return $this->isSubclassOfClass($this->reflectionProvider->getClass($className));
1114: }
1115:
1116: /**
1117: * @deprecated Use isSubclassOfClass instead.
1118: */
1119: public function isSubclassOf(string $className): bool
1120: {
1121: if (!$this->reflectionProvider->hasClass($className)) {
1122: return false;
1123: }
1124:
1125: return $this->isSubclassOfClass($this->reflectionProvider->getClass($className));
1126: }
1127:
1128: public function isSubclassOfClass(self $class): bool
1129: {
1130: $cacheKey = $class->getCacheKey();
1131: if (isset($this->subclasses[$cacheKey])) {
1132: return $this->subclasses[$cacheKey];
1133: }
1134:
1135: if ($class->isFinalByKeyword() || $class->isAnonymous()) {
1136: return $this->subclasses[$cacheKey] = false;
1137: }
1138:
1139: try {
1140: return $this->subclasses[$cacheKey] = $this->reflection->isSubclassOf($class->getName());
1141: } catch (ReflectionException) {
1142: return $this->subclasses[$cacheKey] = false;
1143: }
1144: }
1145:
1146: public function implementsInterface(string $className): bool
1147: {
1148: try {
1149: return $this->reflection->implementsInterface($className);
1150: } catch (ReflectionException) {
1151: return false;
1152: }
1153: }
1154:
1155: /**
1156: * @return list<ClassReflection>
1157: */
1158: public function getParents(): array
1159: {
1160: $parents = [];
1161: $parent = $this->getParentClass();
1162: while ($parent !== null) {
1163: $parents[] = $parent;
1164: $parent = $parent->getParentClass();
1165: }
1166:
1167: return $parents;
1168: }
1169:
1170: /**
1171: * @return array<string, ClassReflection>
1172: */
1173: public function getInterfaces(): array
1174: {
1175: if ($this->cachedInterfaces !== null) {
1176: return $this->cachedInterfaces;
1177: }
1178:
1179: $interfaces = $this->getImmediateInterfaces();
1180: $immediateInterfaces = $interfaces;
1181: $parent = $this->getParentClass();
1182: while ($parent !== null) {
1183: foreach ($parent->getImmediateInterfaces() as $parentInterface) {
1184: $interfaces[$parentInterface->getName()] = $parentInterface;
1185: foreach ($this->collectInterfaces($parentInterface) as $parentInterfaceInterface) {
1186: $interfaces[$parentInterfaceInterface->getName()] = $parentInterfaceInterface;
1187: }
1188: }
1189:
1190: $parent = $parent->getParentClass();
1191: }
1192:
1193: foreach ($immediateInterfaces as $immediateInterface) {
1194: foreach ($this->collectInterfaces($immediateInterface) as $interfaceInterface) {
1195: $interfaces[$interfaceInterface->getName()] = $interfaceInterface;
1196: }
1197: }
1198:
1199: $this->cachedInterfaces = $interfaces;
1200:
1201: return $interfaces;
1202: }
1203:
1204: /**
1205: * @return array<string, ClassReflection>
1206: */
1207: private function collectInterfaces(ClassReflection $interface): array
1208: {
1209: $interfaces = [];
1210: $queue = [$interface];
1211: while ($queue !== []) {
1212: $current = array_pop($queue);
1213: foreach ($current->getImmediateInterfaces() as $immediateInterface) {
1214: $name = $immediateInterface->getName();
1215: if (array_key_exists($name, $interfaces)) {
1216: continue;
1217: }
1218: $interfaces[$name] = $immediateInterface;
1219: $queue[] = $immediateInterface;
1220: }
1221: }
1222:
1223: return $interfaces;
1224: }
1225:
1226: /**
1227: * @return array<string, ClassReflection>
1228: */
1229: public function getImmediateInterfaces(): array
1230: {
1231: $indirectInterfaceNames = [];
1232: $parent = $this->getParentClass();
1233: while ($parent !== null) {
1234: foreach ($parent->getNativeReflection()->getInterfaceNames() as $parentInterfaceName) {
1235: $indirectInterfaceNames[] = $parentInterfaceName;
1236: }
1237:
1238: $parent = $parent->getParentClass();
1239: }
1240:
1241: foreach ($this->getNativeReflection()->getInterfaces() as $interfaceInterface) {
1242: foreach ($interfaceInterface->getInterfaceNames() as $interfaceInterfaceName) {
1243: $indirectInterfaceNames[] = $interfaceInterfaceName;
1244: }
1245: }
1246:
1247: if ($this->reflection->isInterface()) {
1248: $implementsTags = $this->getExtendsTags();
1249: } else {
1250: $implementsTags = $this->getImplementsTags();
1251: }
1252:
1253: $immediateInterfaceNames = array_diff($this->getNativeReflection()->getInterfaceNames(), $indirectInterfaceNames);
1254: $immediateInterfaces = [];
1255: foreach ($immediateInterfaceNames as $immediateInterfaceName) {
1256: if (!$this->reflectionProvider->hasClass($immediateInterfaceName)) {
1257: continue;
1258: }
1259:
1260: $immediateInterface = $this->reflectionProvider->getClass($immediateInterfaceName);
1261: if (array_key_exists($immediateInterface->getName(), $implementsTags)) {
1262: $implementsTag = $implementsTags[$immediateInterface->getName()];
1263: $implementedType = $implementsTag->getType();
1264: if ($this->isGeneric()) {
1265: $implementedType = TemplateTypeHelper::resolveTemplateTypes(
1266: $implementedType,
1267: $this->getActiveTemplateTypeMapForAncestorResolution(),
1268: $this->getCallSiteVarianceMap(),
1269: TemplateTypeVariance::createStatic(),
1270: true,
1271: );
1272: }
1273:
1274: if (
1275: $implementedType instanceof GenericObjectType
1276: && $implementedType->getClassReflection() !== null
1277: ) {
1278: $immediateInterfaces[$immediateInterface->getName()] = $implementedType->getClassReflection();
1279: continue;
1280: }
1281: }
1282:
1283: if ($immediateInterface->isGeneric()) {
1284: $immediateInterfaces[$immediateInterface->getName()] = $immediateInterface->withTypes(
1285: array_values($immediateInterface->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()),
1286: );
1287: continue;
1288: }
1289:
1290: $immediateInterfaces[$immediateInterface->getName()] = $immediateInterface;
1291: }
1292:
1293: return $immediateInterfaces;
1294: }
1295:
1296: /**
1297: * @return array<string, ClassReflection>
1298: */
1299: public function getTraits(bool $recursive = false): array
1300: {
1301: $traits = [];
1302:
1303: if ($recursive) {
1304: foreach ($this->collectTraits($this->getNativeReflection()) as $trait) {
1305: $traits[$trait->getName()] = $trait;
1306: }
1307: } else {
1308: $traits = $this->getNativeReflection()->getTraits();
1309: }
1310:
1311: $traits = array_map(fn (ReflectionClass $trait): ClassReflection => $this->reflectionProvider->getClass($trait->getName()), $traits);
1312:
1313: if ($recursive) {
1314: $parentClass = $this->getParentClass();
1315:
1316: if ($parentClass !== null) {
1317: return array_merge(
1318: $traits,
1319: $parentClass->getTraits(true),
1320: );
1321: }
1322: }
1323:
1324: return $traits;
1325: }
1326:
1327: /**
1328: * @return list<class-string>
1329: */
1330: public function getParentClassesNames(): array
1331: {
1332: $parentNames = [];
1333: $parentClass = $this->getParentClass();
1334: while ($parentClass !== null) {
1335: $parentNames[] = $parentClass->getName();
1336: $parentClass = $parentClass->getParentClass();
1337: }
1338:
1339: return $parentNames;
1340: }
1341:
1342: public function hasConstant(string $name): bool
1343: {
1344: if (!$this->getNativeReflection()->hasConstant($name)) {
1345: return false;
1346: }
1347:
1348: $reflectionConstant = $this->getNativeReflection()->getReflectionConstant($name);
1349: if ($reflectionConstant === false) {
1350: return false;
1351: }
1352:
1353: return $this->reflectionProvider->hasClass($reflectionConstant->getDeclaringClass()->getName());
1354: }
1355:
1356: public function getConstant(string $name): ClassConstantReflection
1357: {
1358: if (!isset($this->constants[$name])) {
1359: $reflectionConstant = $this->getNativeReflection()->getReflectionConstant($name);
1360: if ($reflectionConstant === false) {
1361: throw new MissingConstantFromReflectionException($this->getName(), $name);
1362: }
1363:
1364: $deprecation = $this->deprecationProvider->getClassConstantDeprecation($reflectionConstant);
1365: $deprecatedDescription = $deprecation?->getDescription();
1366: $isDeprecated = $deprecation !== null;
1367:
1368: $declaringClass = $this->getAncestorWithClassName($reflectionConstant->getDeclaringClass()->getName());
1369: if ($declaringClass === null) {
1370: throw new ShouldNotHappenException();
1371: }
1372: $fileName = $declaringClass->getFileName();
1373: $phpDocType = null;
1374: $currentResolvedPhpDoc = $this->findConstantResolvedPhpDoc($reflectionConstant);
1375:
1376: $nativeType = null;
1377: if ($reflectionConstant->getType() !== null) {
1378: $nativeType = TypehintHelper::decideTypeFromReflection($reflectionConstant->getType(), selfClass: $declaringClass);
1379: } elseif ($this->signatureMapProvider->hasClassConstantMetadata($declaringClass->getName(), $name)) {
1380: $nativeType = $this->signatureMapProvider->getClassConstantMetadata($declaringClass->getName(), $name)['nativeType'];
1381: }
1382:
1383: $resolvedPhpDoc = $this->phpDocInheritanceResolver->resolvePhpDocForConstant(
1384: $declaringClass,
1385: $name,
1386: $currentResolvedPhpDoc,
1387: );
1388:
1389: $isInternal = false;
1390: $isFinal = false;
1391: if ($resolvedPhpDoc !== null) {
1392: if (!$isDeprecated) {
1393: $deprecatedDescription = $resolvedPhpDoc->getDeprecatedTag() !== null ? $resolvedPhpDoc->getDeprecatedTag()->getMessage() : null;
1394: $isDeprecated = $resolvedPhpDoc->isDeprecated();
1395: }
1396: $isInternal = $resolvedPhpDoc->isInternal();
1397: $isFinal = $resolvedPhpDoc->isFinal();
1398: $phpDocType = self::resolveConstantVarPhpDocType($resolvedPhpDoc, $nativeType, $declaringClass);
1399: }
1400:
1401: $this->constants[$name] = new RealClassClassConstantReflection(
1402: $this->initializerExprTypeResolver,
1403: $declaringClass,
1404: $reflectionConstant,
1405: $nativeType,
1406: $phpDocType,
1407: $resolvedPhpDoc,
1408: $deprecatedDescription,
1409: $isDeprecated,
1410: $isInternal,
1411: $isFinal,
1412: $this->attributeReflectionFactory->fromNativeReflection($reflectionConstant->getAttributes(), InitializerExprContext::fromClass($declaringClass->getName(), $fileName)),
1413: );
1414: }
1415: return $this->constants[$name];
1416: }
1417:
1418: /**
1419: * Returns the @var PHPDoc type of a class constant, if any.
1420: * Does not walk ancestors, so it's safe to call from class-constant
1421: * type resolution (which re-enters via @extends<value-of<...>>).
1422: *
1423: * @internal
1424: */
1425: public function getConstantPhpDocType(string $name): ?Type
1426: {
1427: $reflectionConstant = $this->getNativeReflection()->getReflectionConstant($name);
1428: if ($reflectionConstant === false) {
1429: return null;
1430: }
1431:
1432: $resolvedPhpDoc = $this->findConstantResolvedPhpDoc($reflectionConstant);
1433: if ($resolvedPhpDoc === null) {
1434: return null;
1435: }
1436:
1437: $nativeType = null;
1438: if ($reflectionConstant->getType() !== null) {
1439: $nativeType = TypehintHelper::decideTypeFromReflection($reflectionConstant->getType());
1440: }
1441:
1442: $declaringClassName = $reflectionConstant->getDeclaringClass()->getName();
1443: if ($declaringClassName === $this->getName()) {
1444: $declaringClass = $this;
1445: } else {
1446: $declaringClass = $this->getAncestorWithClassName($declaringClassName);
1447: if ($declaringClass === null) {
1448: return null;
1449: }
1450: }
1451:
1452: return self::resolveConstantVarPhpDocType($resolvedPhpDoc, $nativeType, $declaringClass);
1453: }
1454:
1455: private function findConstantResolvedPhpDoc(ReflectionClassConstant $reflectionConstant): ?ResolvedPhpDocBlock
1456: {
1457: $declaringClassName = $reflectionConstant->getDeclaringClass()->getName();
1458:
1459: $resolvedPhpDoc = $this->stubPhpDocProvider->findClassConstantPhpDoc(
1460: $declaringClassName,
1461: $reflectionConstant->getName(),
1462: );
1463: if ($resolvedPhpDoc !== null) {
1464: return $resolvedPhpDoc;
1465: }
1466:
1467: $docComment = $reflectionConstant->getDocComment();
1468: if ($docComment === false) {
1469: return null;
1470: }
1471:
1472: return $this->fileTypeMapper->getResolvedPhpDoc(
1473: $reflectionConstant->getDeclaringClass()->getFileName() ?: null,
1474: $declaringClassName,
1475: null,
1476: null,
1477: $docComment,
1478: );
1479: }
1480:
1481: private static function resolveConstantVarPhpDocType(
1482: ResolvedPhpDocBlock $resolvedPhpDoc,
1483: ?Type $nativeType,
1484: self $declaringClass,
1485: ): ?Type
1486: {
1487: $varTags = $resolvedPhpDoc->getVarTags();
1488: if (!isset($varTags[0]) || count($varTags) !== 1) {
1489: return null;
1490: }
1491:
1492: $varTag = $varTags[0];
1493: if (!$varTag->isExplicit() && $nativeType !== null && !$nativeType->isSuperTypeOf($varTag->getType())->yes()) {
1494: return null;
1495: }
1496:
1497: return TemplateTypeHelper::resolveTemplateTypes(
1498: $varTag->getType(),
1499: $declaringClass->getActiveTemplateTypeMap(),
1500: $declaringClass->getCallSiteVarianceMap(),
1501: TemplateTypeVariance::createInvariant(),
1502: );
1503: }
1504:
1505: public function hasTraitUse(string $traitName): bool
1506: {
1507: return in_array($traitName, $this->getTraitNames(), true);
1508: }
1509:
1510: /**
1511: * @return list<string>
1512: */
1513: private function getTraitNames(): array
1514: {
1515: $class = $this->reflection;
1516: $traitNames = array_map(static fn (ReflectionClass $class) => $class->getName(), $this->collectTraits($class));
1517: while ($class->getParentClass() !== false) {
1518: $traitNames = array_values(array_unique(array_merge($traitNames, $class->getParentClass()->getTraitNames())));
1519: $class = $class->getParentClass();
1520: }
1521:
1522: return $traitNames;
1523: }
1524:
1525: /**
1526: * @return array<string, TypeAlias>
1527: */
1528: public function getTypeAliases(): array
1529: {
1530: if ($this->typeAliases === null) {
1531: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1532: if ($resolvedPhpDoc === null) {
1533: return $this->typeAliases = [];
1534: }
1535:
1536: $typeAliasImportTags = $resolvedPhpDoc->getTypeAliasImportTags();
1537: $typeAliasTags = $resolvedPhpDoc->getTypeAliasTags();
1538: $localAliases = array_map(static fn (TypeAliasTag $typeAliasTag): TypeAlias => $typeAliasTag->getTypeAlias(), $typeAliasTags);
1539:
1540: // prevent circular imports
1541: if (array_key_exists($this->getName(), self::$resolvingTypeAliasImports)) {
1542: if ($localAliases !== []) {
1543: return $this->typeAliases = $localAliases;
1544: }
1545: throw new CircularTypeAliasDefinitionException();
1546: }
1547:
1548: self::$resolvingTypeAliasImports[$this->getName()] = true;
1549:
1550: $importedAliases = array_map(function (TypeAliasImportTag $typeAliasImportTag): ?TypeAlias {
1551: $importedAlias = $typeAliasImportTag->getImportedAlias();
1552: $importedFromClassName = $typeAliasImportTag->getImportedFrom();
1553:
1554: if (!$this->reflectionProvider->hasClass($importedFromClassName)) {
1555: return null;
1556: }
1557:
1558: $importedFromReflection = $this->reflectionProvider->getClass($importedFromClassName);
1559:
1560: try {
1561: $typeAliases = $importedFromReflection->getTypeAliases();
1562: } catch (CircularTypeAliasDefinitionException) {
1563: return TypeAlias::invalid();
1564: }
1565:
1566: if (!array_key_exists($importedAlias, $typeAliases)) {
1567: return null;
1568: }
1569:
1570: return $typeAliases[$importedAlias];
1571: }, $typeAliasImportTags);
1572:
1573: unset(self::$resolvingTypeAliasImports[$this->getName()]);
1574:
1575: $this->typeAliases = array_filter(
1576: array_merge($importedAliases, $localAliases),
1577: static fn (?TypeAlias $typeAlias): bool => $typeAlias !== null,
1578: );
1579: }
1580:
1581: return $this->typeAliases;
1582: }
1583:
1584: public function getDeprecatedDescription(): ?string
1585: {
1586: if ($this->isDeprecated === null) {
1587: $this->resolveDeprecation();
1588: }
1589:
1590: return $this->deprecatedDescription;
1591: }
1592:
1593: public function isDeprecated(): bool
1594: {
1595: if ($this->isDeprecated === null) {
1596: $this->resolveDeprecation();
1597: }
1598:
1599: return $this->isDeprecated;
1600: }
1601:
1602: /**
1603: * @phpstan-assert bool $this->isDeprecated
1604: */
1605: private function resolveDeprecation(): void
1606: {
1607: $deprecation = $this->deprecationProvider->getClassDeprecation($this->reflection);
1608: if ($deprecation !== null) {
1609: $this->isDeprecated = true;
1610: $this->deprecatedDescription = $deprecation->getDescription();
1611: return;
1612: }
1613:
1614: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1615:
1616: if ($resolvedPhpDoc !== null && $resolvedPhpDoc->isDeprecated()) {
1617: $this->isDeprecated = true;
1618: $this->deprecatedDescription = $resolvedPhpDoc->getDeprecatedTag() !== null ? $resolvedPhpDoc->getDeprecatedTag()->getMessage() : null;
1619: return;
1620: }
1621:
1622: if ($this->isTrait() && count($this->getNativeReflection()->getAttributes('Deprecated')) > 0) {
1623: $this->isDeprecated = true;
1624: $this->deprecatedDescription = null;
1625: return;
1626: }
1627:
1628: $this->isDeprecated = false;
1629: $this->deprecatedDescription = null;
1630: }
1631:
1632: public function isBuiltin(): bool
1633: {
1634: return $this->reflection->isInternal();
1635: }
1636:
1637: public function isInternal(): bool
1638: {
1639: if ($this->isInternal === null) {
1640: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1641: $this->isInternal = $resolvedPhpDoc !== null && $resolvedPhpDoc->isInternal();
1642: }
1643:
1644: return $this->isInternal;
1645: }
1646:
1647: public function isFinal(): bool
1648: {
1649: if ($this->isFinalByKeyword()) {
1650: return true;
1651: }
1652:
1653: if ($this->isFinal === null) {
1654: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1655: $this->isFinal = $resolvedPhpDoc !== null && $resolvedPhpDoc->isFinal();
1656: }
1657:
1658: return $this->isFinal;
1659: }
1660:
1661: public function isImmutable(): bool
1662: {
1663: if ($this->isImmutable === null) {
1664: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1665: $this->isImmutable = $resolvedPhpDoc !== null && ($resolvedPhpDoc->isImmutable() || $resolvedPhpDoc->isReadOnly());
1666:
1667: $parentClass = $this->getParentClass();
1668: if ($parentClass !== null && !$this->isImmutable) {
1669: $this->isImmutable = $parentClass->isImmutable();
1670: }
1671: }
1672:
1673: return $this->isImmutable;
1674: }
1675:
1676: public function hasConsistentConstructor(): bool
1677: {
1678: if ($this->hasConsistentConstructor === null) {
1679: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1680: $this->hasConsistentConstructor = $resolvedPhpDoc !== null && $resolvedPhpDoc->hasConsistentConstructor();
1681: }
1682:
1683: return $this->hasConsistentConstructor;
1684: }
1685:
1686: public function acceptsNamedArguments(): bool
1687: {
1688: if ($this->acceptsNamedArguments === null) {
1689: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1690: $this->acceptsNamedArguments = $resolvedPhpDoc === null || $resolvedPhpDoc->acceptsNamedArguments();
1691: }
1692:
1693: return $this->acceptsNamedArguments;
1694: }
1695:
1696: public function hasFinalByKeywordOverride(): bool
1697: {
1698: return $this->finalByKeywordOverride !== null;
1699: }
1700:
1701: public function isFinalByKeyword(): bool
1702: {
1703: if ($this->isAnonymous()) {
1704: return true;
1705: }
1706:
1707: if ($this->finalByKeywordOverride !== null) {
1708: return $this->finalByKeywordOverride;
1709: }
1710:
1711: return $this->reflection->isFinal();
1712: }
1713:
1714: public function isAttributeClass(): bool
1715: {
1716: return $this->findAttributeFlags() !== null;
1717: }
1718:
1719: private function findAttributeFlags(): ?int
1720: {
1721: if ($this->isInterface() || $this->isTrait() || $this->isEnum()) {
1722: return null;
1723: }
1724:
1725: $nativeAttributes = $this->reflection->getAttributes(Attribute::class);
1726: if (count($nativeAttributes) === 1) {
1727: if (!$this->reflectionProvider->hasClass(Attribute::class)) {
1728: return null;
1729: }
1730:
1731: $attributeClass = $this->reflectionProvider->getClass(Attribute::class);
1732: $arguments = [];
1733: foreach ($nativeAttributes[0]->getArgumentsExpressions() as $i => $expression) {
1734: if ($i === '') {
1735: throw new ShouldNotHappenException();
1736: }
1737: $arguments[] = new Arg($expression, name: is_int($i) ? null : new Identifier($i));
1738: }
1739:
1740: if (!$attributeClass->hasConstructor()) {
1741: return null;
1742: }
1743: $attributeConstructor = $attributeClass->getConstructor();
1744: $attributeConstructorVariant = $attributeConstructor->getOnlyVariant();
1745:
1746: if (count($arguments) === 0) {
1747: $flagType = $attributeConstructorVariant->getParameters()[0]->getDefaultValue();
1748: } else {
1749: $staticCall = ArgumentsNormalizer::reorderStaticCallArguments(
1750: $attributeConstructorVariant,
1751: new StaticCall(new FullyQualified(Attribute::class), $attributeConstructor->getName(), $arguments),
1752: );
1753: if ($staticCall === null) {
1754: return null;
1755: }
1756: $flagExpr = $staticCall->getArgs()[0]->value;
1757: $flagType = $this->initializerExprTypeResolver->getType($flagExpr, InitializerExprContext::fromClassReflection($this));
1758: }
1759:
1760: if (!$flagType instanceof ConstantIntegerType) {
1761: return null;
1762: }
1763:
1764: return $flagType->getValue();
1765: }
1766:
1767: return null;
1768: }
1769:
1770: /**
1771: * @return list<AttributeReflection>
1772: */
1773: public function getAttributes(): array
1774: {
1775: return $this->attributeReflectionFactory->fromNativeReflection($this->reflection->getAttributes(), InitializerExprContext::fromClass($this->getName(), $this->getFileName()));
1776: }
1777:
1778: public function getAttributeClassFlags(): int
1779: {
1780: $flags = $this->findAttributeFlags();
1781: if ($flags === null) {
1782: throw new ShouldNotHappenException();
1783: }
1784:
1785: return $flags;
1786: }
1787:
1788: public function getObjectType(): ObjectType
1789: {
1790: if (!$this->isGeneric()) {
1791: return new ObjectType($this->getName());
1792: }
1793:
1794: return new GenericObjectType(
1795: $this->getName(),
1796: $this->typeMapToList($this->getActiveTemplateTypeMap()),
1797: variances: $this->varianceMapToList($this->getCallSiteVarianceMap()),
1798: );
1799: }
1800:
1801: public function getTemplateTypeMap(): TemplateTypeMap
1802: {
1803: if ($this->templateTypeMap !== null) {
1804: return $this->templateTypeMap;
1805: }
1806:
1807: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1808: if ($resolvedPhpDoc === null) {
1809: $this->templateTypeMap = TemplateTypeMap::createEmpty();
1810: return $this->templateTypeMap;
1811: }
1812:
1813: $templateTypeScope = TemplateTypeScope::createWithClass($this->getName());
1814:
1815: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $this->getTemplateTags()));
1816:
1817: $this->templateTypeMap = $templateTypeMap;
1818:
1819: return $templateTypeMap;
1820: }
1821:
1822: public function getActiveTemplateTypeMap(): TemplateTypeMap
1823: {
1824: if ($this->activeTemplateTypeMap !== null) {
1825: return $this->activeTemplateTypeMap;
1826: }
1827: $resolved = $this->resolvedTemplateTypeMap;
1828: if ($resolved !== null) {
1829: $templateTypeMap = $this->getTemplateTypeMap();
1830: return $this->activeTemplateTypeMap = $resolved->map(static function (string $name, Type $type) use ($templateTypeMap): Type {
1831: if ($type instanceof ErrorType) {
1832: $templateType = $templateTypeMap->getType($name);
1833: if ($templateType !== null) {
1834: return TemplateTypeHelper::resolveToDefaults($templateType);
1835: }
1836: }
1837:
1838: return $type;
1839: });
1840: }
1841:
1842: return $this->activeTemplateTypeMap = $this->getTemplateTypeMap();
1843: }
1844:
1845: public function getPossiblyIncompleteActiveTemplateTypeMap(): TemplateTypeMap
1846: {
1847: return $this->resolvedTemplateTypeMap ?? $this->getTemplateTypeMap();
1848: }
1849:
1850: /**
1851: * Returns a template type map for resolving ancestor type declarations (@extends, @implements).
1852: * Like getPossiblyIncompleteActiveTemplateTypeMap(), but resolves ErrorType entries
1853: * to their template bounds when the bound is not mixed. This ensures that when a child
1854: * class narrows a template bound (e.g. `@template T of SpecificType`), the narrowed bound
1855: * is propagated to ancestor declarations instead of being lost as ErrorType.
1856: */
1857: private function getActiveTemplateTypeMapForAncestorResolution(): TemplateTypeMap
1858: {
1859: $map = $this->getPossiblyIncompleteActiveTemplateTypeMap();
1860: $templateTypeMap = $this->getTemplateTypeMap();
1861:
1862: return $map->map(static function (string $name, Type $type) use ($templateTypeMap): Type {
1863: if (!$type instanceof ErrorType) {
1864: return $type;
1865: }
1866:
1867: $templateType = $templateTypeMap->getType($name);
1868: if (!$templateType instanceof TemplateType) {
1869: return $type;
1870: }
1871:
1872: $bound = $templateType->getBound();
1873: if ($bound instanceof MixedType) {
1874: return $type;
1875: }
1876:
1877: return TemplateTypeHelper::resolveToDefaults($templateType);
1878: });
1879: }
1880:
1881: private function getDefaultCallSiteVarianceMap(): TemplateTypeVarianceMap
1882: {
1883: if ($this->defaultCallSiteVarianceMap !== null) {
1884: return $this->defaultCallSiteVarianceMap;
1885: }
1886:
1887: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1888: if ($resolvedPhpDoc === null) {
1889: $this->defaultCallSiteVarianceMap = TemplateTypeVarianceMap::createEmpty();
1890: return $this->defaultCallSiteVarianceMap;
1891: }
1892:
1893: $map = [];
1894: foreach ($this->getTemplateTags() as $templateTag) {
1895: $map[$templateTag->getName()] = TemplateTypeVariance::createInvariant();
1896: }
1897:
1898: $this->defaultCallSiteVarianceMap = new TemplateTypeVarianceMap($map);
1899: return $this->defaultCallSiteVarianceMap;
1900: }
1901:
1902: public function getCallSiteVarianceMap(): TemplateTypeVarianceMap
1903: {
1904: return $this->callSiteVarianceMap ??= $this->resolvedCallSiteVarianceMap ?? $this->getDefaultCallSiteVarianceMap();
1905: }
1906:
1907: public function isGeneric(): bool
1908: {
1909: if ($this->isGeneric === null) {
1910: if ($this->isEnum()) {
1911: return $this->isGeneric = false;
1912: }
1913:
1914: $isGeneric = count($this->getTemplateTags()) > 0;
1915: if ($this->fileTypeMapper->isClassNameScopeBeingCreated($this->getName())) {
1916: return $isGeneric;
1917: }
1918:
1919: $this->isGeneric = $isGeneric;
1920: }
1921:
1922: return $this->isGeneric;
1923: }
1924:
1925: /**
1926: * @param array<int, Type> $types
1927: */
1928: public function typeMapFromList(array $types): TemplateTypeMap
1929: {
1930: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1931: if ($resolvedPhpDoc === null) {
1932: return TemplateTypeMap::createEmpty();
1933: }
1934:
1935: $map = [];
1936: $i = 0;
1937: $className = $this->getName();
1938: foreach ($resolvedPhpDoc->getTemplateTags() as $tag) {
1939: $type = $types[$i] ?? $tag->getDefault() ?? $tag->getBound();
1940: // A template default may reference other template types of the same
1941: // class, possibly nested inside a composite type like `TValue|null`.
1942: // Never descend into a TemplateType's bound - bounds may be
1943: // self-referential (`@template T of Foo<T>`).
1944: $type = TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($map, $className): Type {
1945: if (!$type instanceof TemplateType) {
1946: return $traverse($type);
1947: }
1948:
1949: if ($type->getScope()->getClassName() !== $className) {
1950: return $type;
1951: }
1952:
1953: $resolved = $map[$type->getName()] ?? null;
1954: if ($resolved !== null && !$resolved instanceof TemplateType) {
1955: return $resolved;
1956: }
1957:
1958: return $type;
1959: });
1960: $map[$tag->getName()] = $type;
1961: $i++;
1962: }
1963:
1964: return new TemplateTypeMap($map);
1965: }
1966:
1967: /**
1968: * @param array<int, TemplateTypeVariance> $variances
1969: */
1970: public function varianceMapFromList(array $variances): TemplateTypeVarianceMap
1971: {
1972: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1973: if ($resolvedPhpDoc === null) {
1974: return new TemplateTypeVarianceMap([]);
1975: }
1976:
1977: $map = [];
1978: $i = 0;
1979: foreach ($resolvedPhpDoc->getTemplateTags() as $tag) {
1980: $map[$tag->getName()] = $variances[$i] ?? TemplateTypeVariance::createInvariant();
1981: $i++;
1982: }
1983:
1984: return new TemplateTypeVarianceMap($map);
1985: }
1986:
1987: /** @return list<Type> */
1988: public function typeMapToList(TemplateTypeMap $typeMap): array
1989: {
1990: $resolvedPhpDoc = $this->getResolvedPhpDoc();
1991: if ($resolvedPhpDoc === null) {
1992: return [];
1993: }
1994:
1995: $list = [];
1996: foreach ($resolvedPhpDoc->getTemplateTags() as $tag) {
1997: $list[] = $typeMap->getType($tag->getName()) ?? $tag->getDefault() ?? $tag->getBound();
1998: }
1999:
2000: return $list;
2001: }
2002:
2003: /** @return list<TemplateTypeVariance> */
2004: public function varianceMapToList(TemplateTypeVarianceMap $varianceMap): array
2005: {
2006: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2007: if ($resolvedPhpDoc === null) {
2008: return [];
2009: }
2010:
2011: $list = [];
2012: foreach ($resolvedPhpDoc->getTemplateTags() as $tag) {
2013: $list[] = $varianceMap->getVariance($tag->getName()) ?? TemplateTypeVariance::createInvariant();
2014: }
2015:
2016: return $list;
2017: }
2018:
2019: /**
2020: * @param array<int, Type> $types
2021: */
2022: public function withTypes(array $types): self
2023: {
2024: return $this->classReflectionFactory->create(
2025: $this->displayName,
2026: $this->reflection,
2027: $this->anonymousFilename,
2028: $this->typeMapFromList($types),
2029: $this->stubPhpDocBlockCallback,
2030: null,
2031: $this->resolvedCallSiteVarianceMap,
2032: $this->finalByKeywordOverride,
2033: );
2034: }
2035:
2036: /**
2037: * @param array<int, TemplateTypeVariance> $variances
2038: */
2039: public function withVariances(array $variances): self
2040: {
2041: return $this->classReflectionFactory->create(
2042: $this->displayName,
2043: $this->reflection,
2044: $this->anonymousFilename,
2045: $this->resolvedTemplateTypeMap,
2046: $this->stubPhpDocBlockCallback,
2047: null,
2048: $this->varianceMapFromList($variances),
2049: $this->finalByKeywordOverride,
2050: );
2051: }
2052:
2053: public function asFinal(): self
2054: {
2055: if ($this->getNativeReflection()->isFinal()) {
2056: return $this;
2057: }
2058: if ($this->finalByKeywordOverride === true) {
2059: return $this;
2060: }
2061: if (!$this->isClass()) {
2062: return $this;
2063: }
2064: if ($this->isAbstract()) {
2065: return $this;
2066: }
2067:
2068: return $this->classReflectionFactory->create(
2069: $this->displayName,
2070: $this->reflection,
2071: $this->anonymousFilename,
2072: $this->resolvedTemplateTypeMap,
2073: $this->stubPhpDocBlockCallback,
2074: null,
2075: $this->resolvedCallSiteVarianceMap,
2076: true,
2077: );
2078: }
2079:
2080: /**
2081: * Back to the finality the class declares. Unlike removeFinalKeywordOverride(),
2082: * which asserts non-finality, this drops the override altogether - a type holding
2083: * such a reflection stops claiming to be exactly this class.
2084: */
2085: public function withoutFinalByKeywordOverride(): self
2086: {
2087: if ($this->finalByKeywordOverride === null) {
2088: return $this;
2089: }
2090:
2091: return $this->classReflectionFactory->create(
2092: $this->displayName,
2093: $this->reflection,
2094: $this->anonymousFilename,
2095: $this->resolvedTemplateTypeMap,
2096: $this->stubPhpDocBlockCallback,
2097: null,
2098: $this->resolvedCallSiteVarianceMap,
2099: null,
2100: );
2101: }
2102:
2103: public function removeFinalKeywordOverride(): self
2104: {
2105: if ($this->getNativeReflection()->isFinal()) {
2106: return $this;
2107: }
2108: if ($this->finalByKeywordOverride === false) {
2109: return $this;
2110: }
2111: if (!$this->isClass()) {
2112: return $this;
2113: }
2114: if ($this->isAbstract()) {
2115: return $this;
2116: }
2117:
2118: return $this->classReflectionFactory->create(
2119: $this->displayName,
2120: $this->reflection,
2121: $this->anonymousFilename,
2122: $this->resolvedTemplateTypeMap,
2123: $this->stubPhpDocBlockCallback,
2124: null,
2125: $this->resolvedCallSiteVarianceMap,
2126: false,
2127: );
2128: }
2129:
2130: public function getResolvedPhpDoc(): ?ResolvedPhpDocBlock
2131: {
2132: if ($this->stubPhpDocBlockCallback !== null) {
2133: if ($this->stubPhpDocBlock === false) {
2134: $this->stubPhpDocBlock = ($this->stubPhpDocBlockCallback)();
2135: }
2136: if ($this->stubPhpDocBlock !== null) {
2137: return $this->stubPhpDocBlock;
2138: }
2139: }
2140:
2141: $fileName = $this->getFileName();
2142: if (is_bool($this->reflectionDocComment)) {
2143: $docComment = $this->reflection->getDocComment();
2144: $this->reflectionDocComment = $docComment !== false ? $docComment : null;
2145: }
2146:
2147: if ($this->reflectionDocComment === null) {
2148: return null;
2149: }
2150:
2151: if ($this->resolvedPhpDocBlock !== false) {
2152: return $this->resolvedPhpDocBlock;
2153: }
2154:
2155: $resolvedPhpDocBlock = $this->fileTypeMapper->getResolvedPhpDoc($fileName, $this->getName(), null, null, $this->reflectionDocComment);
2156: if ($this->fileTypeMapper->isClassNameScopeBeingCreated($this->getName())) {
2157: return $resolvedPhpDocBlock;
2158: }
2159:
2160: return $this->resolvedPhpDocBlock = $resolvedPhpDocBlock;
2161: }
2162:
2163: public function getTraitContextResolvedPhpDoc(self $implementingClass): ?ResolvedPhpDocBlock
2164: {
2165: if (!$this->isTrait()) {
2166: throw new ShouldNotHappenException();
2167: }
2168: if ($implementingClass->isTrait()) {
2169: throw new ShouldNotHappenException();
2170: }
2171: $fileName = $this->getFileName();
2172: if (is_bool($this->reflectionDocComment)) {
2173: $docComment = $this->reflection->getDocComment();
2174: $this->reflectionDocComment = $docComment !== false ? $docComment : null;
2175: }
2176:
2177: if ($this->reflectionDocComment === null) {
2178: return null;
2179: }
2180:
2181: if ($this->traitContextResolvedPhpDocBlock !== false) {
2182: return $this->traitContextResolvedPhpDocBlock;
2183: }
2184:
2185: return $this->traitContextResolvedPhpDocBlock = $this->fileTypeMapper->getResolvedPhpDoc($fileName, $implementingClass->getName(), $this->getName(), null, $this->reflectionDocComment);
2186: }
2187:
2188: private function getFirstExtendsTag(): ?ExtendsTag
2189: {
2190: foreach ($this->getExtendsTags() as $tag) {
2191: return $tag;
2192: }
2193:
2194: return null;
2195: }
2196:
2197: /** @return array<string, ExtendsTag> */
2198: public function getExtendsTags(): array
2199: {
2200: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2201: if ($resolvedPhpDoc === null) {
2202: return [];
2203: }
2204:
2205: return $resolvedPhpDoc->getExtendsTags();
2206: }
2207:
2208: /** @return array<string, ImplementsTag> */
2209: public function getImplementsTags(): array
2210: {
2211: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2212: if ($resolvedPhpDoc === null) {
2213: return [];
2214: }
2215:
2216: return $resolvedPhpDoc->getImplementsTags();
2217: }
2218:
2219: /** @return array<string,TemplateTag> */
2220: public function getTemplateTags(): array
2221: {
2222: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2223: if ($resolvedPhpDoc === null) {
2224: return [];
2225: }
2226:
2227: return $resolvedPhpDoc->getTemplateTags();
2228: }
2229:
2230: /**
2231: * @return array<string,ClassReflection>
2232: */
2233: public function getAncestors(): array
2234: {
2235: if ($this->ancestors === null) {
2236: $ancestors = [
2237: $this->getName() => $this,
2238: ];
2239: $this->collectAncestors($ancestors);
2240:
2241: // the cached array must not contain $this: that would be a reference
2242: // cycle, and with gc_disable() a ClassReflection the reflection provider
2243: // does not keep, like a withTypes() copy, would then never be freed
2244: unset($ancestors[$this->getName()]);
2245: $this->ancestors = $ancestors;
2246: }
2247:
2248: return [$this->getName() => $this] + $this->ancestors;
2249: }
2250:
2251: /**
2252: * Descends into the interfaces, traits and parent classes, using the collected ancestors
2253: * as the set of already visited classes. Traits can use each other in a cycle, which is a
2254: * fatal error in PHP but must not make this walk run forever.
2255: *
2256: * @param array<string, ClassReflection> $ancestors
2257: */
2258: private function collectAncestors(array &$ancestors): void
2259: {
2260: $addToAncestors = static function (ClassReflection $classReflection) use (&$ancestors): void {
2261: if (array_key_exists($classReflection->getName(), $ancestors)) {
2262: return;
2263: }
2264:
2265: $ancestors[$classReflection->getName()] = $classReflection;
2266: $classReflection->collectAncestors($ancestors);
2267: };
2268:
2269: foreach ($this->getInterfaces() as $interface) {
2270: $addToAncestors($interface);
2271: }
2272:
2273: foreach ($this->getTraits() as $trait) {
2274: $addToAncestors($trait);
2275: }
2276:
2277: $parent = $this->getParentClass();
2278: if ($parent === null) {
2279: return;
2280: }
2281:
2282: $addToAncestors($parent);
2283: }
2284:
2285: public function getAncestorWithClassName(string $className): ?self
2286: {
2287: return $this->getAncestors()[$className] ?? null;
2288: }
2289:
2290: /**
2291: * @param string[] $ancestorClasses
2292: */
2293: private function isValidAncestorType(Type $type, array $ancestorClasses): bool
2294: {
2295: if (!$type instanceof GenericObjectType) {
2296: return false;
2297: }
2298:
2299: $reflection = $type->getClassReflection();
2300: if ($reflection === null) {
2301: return false;
2302: }
2303:
2304: return in_array($reflection->getName(), $ancestorClasses, true);
2305: }
2306:
2307: /**
2308: * @return array<MixinTag>
2309: */
2310: public function getMixinTags(): array
2311: {
2312: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2313: if ($resolvedPhpDoc === null) {
2314: return [];
2315: }
2316:
2317: return $resolvedPhpDoc->getMixinTags();
2318: }
2319:
2320: /**
2321: * @return array<RequireExtendsTag>
2322: */
2323: public function getRequireExtendsTags(): array
2324: {
2325: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2326: if ($resolvedPhpDoc === null) {
2327: return [];
2328: }
2329:
2330: return $resolvedPhpDoc->getRequireExtendsTags();
2331: }
2332:
2333: /**
2334: * @return array<RequireImplementsTag>
2335: */
2336: public function getRequireImplementsTags(): array
2337: {
2338: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2339: if ($resolvedPhpDoc === null) {
2340: return [];
2341: }
2342:
2343: return $resolvedPhpDoc->getRequireImplementsTags();
2344: }
2345:
2346: /**
2347: * @return array<SealedTypeTag>
2348: */
2349: public function getSealedTags(): array
2350: {
2351: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2352: if ($resolvedPhpDoc === null) {
2353: return [];
2354: }
2355:
2356: return $resolvedPhpDoc->getSealedTags();
2357: }
2358:
2359: /**
2360: * @return array<string, PropertyTag>
2361: */
2362: public function getPropertyTags(): array
2363: {
2364: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2365: if ($resolvedPhpDoc === null) {
2366: return [];
2367: }
2368:
2369: return $resolvedPhpDoc->getPropertyTags();
2370: }
2371:
2372: /**
2373: * @return array<string, MethodTag>
2374: */
2375: public function getMethodTags(): array
2376: {
2377: $resolvedPhpDoc = $this->getResolvedPhpDoc();
2378: if ($resolvedPhpDoc === null) {
2379: return [];
2380: }
2381:
2382: return $resolvedPhpDoc->getMethodTags();
2383: }
2384:
2385: /**
2386: * @return list<Type>
2387: */
2388: public function getResolvedMixinTypes(): array
2389: {
2390: $types = [];
2391: foreach ($this->getMixinTags() as $mixinTag) {
2392: if (!$this->isGeneric()) {
2393: $types[] = $mixinTag->getType();
2394: continue;
2395: }
2396:
2397: $types[] = TemplateTypeHelper::resolveTemplateTypes(
2398: $mixinTag->getType(),
2399: $this->getActiveTemplateTypeMap(),
2400: $this->getCallSiteVarianceMap(),
2401: TemplateTypeVariance::createStatic(),
2402: );
2403: }
2404:
2405: return $types;
2406: }
2407:
2408: /**
2409: * @return array<Type>|null
2410: */
2411: public function getAllowedSubTypes(): ?array
2412: {
2413: if ($this->allowedSubTypesResolved) {
2414: return $this->allowedSubTypes;
2415: }
2416:
2417: $this->allowedSubTypesResolved = true;
2418: foreach ($this->classReflectionExtensionRegistryProvider->getRegistry()->getAllowedSubTypesClassReflectionExtensions() as $allowedSubTypesClassReflectionExtension) {
2419: if ($allowedSubTypesClassReflectionExtension->supports($this)) {
2420: return $this->allowedSubTypes = $allowedSubTypesClassReflectionExtension->getAllowedSubTypes($this);
2421: }
2422: }
2423:
2424: return null;
2425: }
2426:
2427: }
2428: