1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use ArrayAccess;
6: use ArrayObject;
7: use Closure;
8: use Countable;
9: use DateTimeInterface;
10: use Iterator;
11: use IteratorAggregate;
12: use PhpParser\Node\Name\FullyQualified;
13: use PHPStan\Analyser\OutOfClassScope;
14: use PHPStan\Broker\ClassNotFoundException;
15: use PHPStan\Internal\LruCache;
16: use PHPStan\Php\PhpVersion;
17: use PHPStan\PhpDocParser\Ast\Type\FullyQualifiedNameNode;
18: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
19: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
20: use PHPStan\Reflection\Callables\FunctionCallableVariant;
21: use PHPStan\Reflection\ClassConstantReflection;
22: use PHPStan\Reflection\ClassMemberAccessAnswerer;
23: use PHPStan\Reflection\ClassReflection;
24: use PHPStan\Reflection\Dummy\DummyPropertyReflection;
25: use PHPStan\Reflection\ExtendedMethodReflection;
26: use PHPStan\Reflection\ExtendedPropertyReflection;
27: use PHPStan\Reflection\Php\UniversalObjectCratesClassReflectionExtension;
28: use PHPStan\Reflection\ReflectionProvider;
29: use PHPStan\Reflection\ReflectionProviderStaticAccessor;
30: use PHPStan\Reflection\TrivialParametersAcceptor;
31: use PHPStan\Reflection\Type\CallbackUnresolvedPropertyPrototypeReflection;
32: use PHPStan\Reflection\Type\CalledOnTypeUnresolvedMethodPrototypeReflection;
33: use PHPStan\Reflection\Type\CalledOnTypeUnresolvedPropertyPrototypeReflection;
34: use PHPStan\Reflection\Type\UnionTypeUnresolvedPropertyPrototypeReflection;
35: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
36: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
37: use PHPStan\ShouldNotHappenException;
38: use PHPStan\TrinaryLogic;
39: use PHPStan\Turbo\ShadowedByTurboExtension;
40: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
41: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
42: use PHPStan\Type\Accessory\AccessoryNumericStringType;
43: use PHPStan\Type\Accessory\HasOffsetValueType;
44: use PHPStan\Type\Constant\ConstantArrayType;
45: use PHPStan\Type\Constant\ConstantBooleanType;
46: use PHPStan\Type\Constant\ConstantStringType;
47: use PHPStan\Type\Enum\EnumCaseObjectType;
48: use PHPStan\Type\Generic\GenericClassStringType;
49: use PHPStan\Type\Generic\GenericObjectType;
50: use PHPStan\Type\Generic\TemplateTypeHelper;
51: use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
52: use PHPStan\Type\Traits\MaybeIterableTypeTrait;
53: use PHPStan\Type\Traits\NonArrayTypeTrait;
54: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
55: use PHPStan\Type\Traits\NonGenericTypeTrait;
56: use PHPStan\Type\Traits\OperatorTypeTrait;
57: use PHPStan\Type\Traits\SubstractableTypeTrait;
58: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
59: use Stringable;
60: use Throwable;
61: use Traversable;
62: use function array_key_exists;
63: use function array_map;
64: use function array_merge;
65: use function array_values;
66: use function count;
67: use function get_class;
68: use function implode;
69: use function in_array;
70: use function sprintf;
71: use function strtolower;
72:
73: /** @api */
74: #[InstanceofDeprecated(insteadUse: 'Type::isObject() or Type::getObjectClassNames()')]
75: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ObjectType.cpp')]
76: class ObjectType implements TypeWithClassName, SubtractableType
77: {
78:
79: use MaybeIterableTypeTrait;
80: use NonArrayTypeTrait;
81: use NonGenericTypeTrait;
82: use UndecidedComparisonTypeTrait;
83: use NonGeneralizableTypeTrait;
84: use SubstractableTypeTrait;
85: use OperatorTypeTrait;
86:
87: private const DESCRIPTION_CACHE_LIMIT = 1024;
88:
89: private const EXTRA_OFFSET_CLASSES = [
90: 'DOMNamedNodeMap', // Only read and existence
91: 'Dom\NamedNodeMap', // Only read and existence
92: 'DOMNodeList', // Only read and existence
93: 'Dom\NodeList', // Only read and existence
94: 'Dom\HTMLCollection', // Only read and existence
95: 'Dom\DtdNamedNodeMap', // Only read and existence
96: 'PDORow', // Only read and existence
97: 'ResourceBundle', // Only read
98: 'FFI\CData', // Very funky and weird
99: 'SimpleXMLElement',
100: 'Threaded',
101: ];
102:
103: private ?Type $subtractedType;
104:
105: /** @var array<string, array<string, IsSuperTypeOfResult>> */
106: private static array $superTypes = [];
107:
108: private ?self $cachedParent = null;
109:
110: /** @var self[]|null */
111: private ?array $cachedInterfaces = null;
112:
113: /** @var array<string, array<string, array<string, UnresolvedMethodPrototypeReflection>>> */
114: private static array $methods = [];
115:
116: /** @var array<string, array<string, array<string, UnresolvedPropertyPrototypeReflection>>> */
117: private static array $properties = [];
118:
119: /** @var array<string, array<string, array<string, UnresolvedPropertyPrototypeReflection>>> */
120: private static array $instanceProperties = [];
121:
122: /** @var array<string, array<string, array<string, UnresolvedPropertyPrototypeReflection>>> */
123: private static array $staticProperties = [];
124:
125: /** @var array<string, array<string, self|null>> */
126: private static array $ancestors = [];
127:
128: /** @var array<string, self|null> */
129: private array $currentAncestors = [];
130:
131: private ?string $cachedDescription = null;
132:
133: /**
134: * The class name as the reflection spells it - the properly cased name, or the
135: * readable `class@anonymous...` form. Resolving it takes two ReflectionProvider
136: * round-trips and both the type-only and the value level need it, the latter on
137: * every operation RecursionGuard guards.
138: */
139: private ?string $cachedPreciseName = null;
140:
141: /**
142: * The reflection resolved on demand by getClassReflection(), kept apart from the one
143: * handed to the constructor. The constructor's reflection is part of the type's value
144: * — it can differ from what the provider would return (an anonymous class is identified
145: * by its start line, a final-by-keyword override changes subtyping) — and so it belongs
146: * in the cache key. A lazily fetched one is merely a cache: folding it into the key made
147: * describe(VerbosityLevel::cache()) depend on whether the fetch had happened yet, which
148: * made TypeCombinator::union() — which dedupes on that key — depend on cache warmth
149: * rather than on its arguments' values.
150: */
151: private ?ClassReflection $lazyClassReflection = null;
152:
153: /**
154: * What getClassReflection() returns, made once: for a generic class the reflection with its
155: * template types erased. Kept apart from the two above, which the other methods read with
156: * the template types in place.
157: */
158: private ?ClassReflection $returnedClassReflection = null;
159:
160: /** @var array<string, list<EnumCaseObjectType>> */
161: private static array $enumCases = [];
162:
163: /** @var LruCache<true>|null shared LRU over the description keys of the static caches above */
164: private static ?LruCache $descriptionCacheOrder = null;
165:
166: /** consecutive lookups mostly touch the same description — skip the LRU bookkeeping for them */
167: private static ?string $lastTouchedDescription = null;
168:
169: /** @var array<string, ExtendedMethodReflection> */
170: private array $methodCache = [];
171:
172: /** @api */
173: public function __construct(
174: private string $className,
175: ?Type $subtractedType = null,
176: private ?ClassReflection $classReflection = null,
177: )
178: {
179: if ($subtractedType instanceof NeverType) {
180: $subtractedType = null;
181: }
182:
183: $this->subtractedType = $subtractedType;
184: }
185:
186: public static function resetCaches(): void
187: {
188: self::$superTypes = [];
189: self::$methods = [];
190: self::$properties = [];
191: self::$instanceProperties = [];
192: self::$staticProperties = [];
193: self::$ancestors = [];
194: self::$enumCases = [];
195: self::$descriptionCacheOrder = null;
196: self::$lastTouchedDescription = null;
197: }
198:
199: /**
200: * Moves the description to the most-recently-used position of the shared LRU
201: * governing the static caches above; evicts the least recently used description's
202: * entries from all of them once the limit is reached. Misses are pure recomputation.
203: */
204: private static function touchDescriptionCacheKey(string $description): void
205: {
206: if ($description === self::$lastTouchedDescription) {
207: return;
208: }
209: self::$lastTouchedDescription = $description;
210:
211: self::$descriptionCacheOrder ??= new LruCache(self::DESCRIPTION_CACHE_LIMIT);
212: if (self::$descriptionCacheOrder->get($description) !== null) {
213: return;
214: }
215:
216: foreach (self::$descriptionCacheOrder->set($description, true, 0) as $evictKey) {
217: unset(
218: self::$superTypes[$evictKey],
219: self::$methods[$evictKey],
220: self::$properties[$evictKey],
221: self::$instanceProperties[$evictKey],
222: self::$staticProperties[$evictKey],
223: self::$ancestors[$evictKey],
224: self::$enumCases[$evictKey],
225: );
226: }
227: }
228:
229: public function getClassName(): string
230: {
231: return $this->className;
232: }
233:
234: public function hasProperty(string $propertyName): TrinaryLogic
235: {
236: $classReflection = $this->getClassReflection();
237: if ($classReflection === null) {
238: return TrinaryLogic::createMaybe();
239: }
240:
241: $classHasProperty = RecursionGuard::run($this, static fn (): bool => $classReflection->hasProperty($propertyName));
242: if ($classHasProperty === true || $classHasProperty instanceof ErrorType) {
243: return TrinaryLogic::createYes();
244: }
245:
246: if ($classReflection->allowsDynamicProperties()) {
247: return TrinaryLogic::createMaybe();
248: }
249:
250: if (!$classReflection->isFinal()) {
251: return TrinaryLogic::createMaybe();
252: }
253:
254: return TrinaryLogic::createNo();
255: }
256:
257: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
258: {
259: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
260: }
261:
262: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
263: {
264: if (!$scope->isInClass()) {
265: $canAccessProperty = 'no';
266: } else {
267: $canAccessProperty = $scope->getClassReflection()->getName();
268: }
269: $description = $this->describeCache();
270:
271: self::touchDescriptionCacheKey($description);
272:
273: if (isset(self::$properties[$description][$propertyName][$canAccessProperty])) {
274: return self::$properties[$description][$propertyName][$canAccessProperty];
275: }
276:
277: $nakedClassReflection = $this->getNakedClassReflection();
278: if ($nakedClassReflection === null) {
279: throw new ClassNotFoundException($this->className);
280: }
281:
282: if ($nakedClassReflection->isEnum()) {
283: if (
284: $propertyName === 'name'
285: || ($propertyName === 'value' && $nakedClassReflection->isBackedEnum())
286: ) {
287: $properties = [];
288: foreach ($this->getEnumCases() as $enumCase) {
289: $properties[] = $enumCase->getUnresolvedPropertyPrototype($propertyName, $scope);
290: }
291:
292: if (count($properties) > 0) {
293: if (count($properties) === 1) {
294: return $properties[0];
295: }
296:
297: return new UnionTypeUnresolvedPropertyPrototypeReflection($properties);
298: }
299: }
300: }
301:
302: if (!$nakedClassReflection->hasNativeProperty($propertyName)) {
303: $nakedClassReflection = $this->getClassReflection();
304: }
305:
306: if ($nakedClassReflection === null) {
307: throw new ClassNotFoundException($this->className);
308: }
309:
310: $property = RecursionGuard::run($this, static fn () => $nakedClassReflection->getProperty($propertyName, $scope));
311: if ($property instanceof ErrorType) {
312: $property = new DummyPropertyReflection($propertyName);
313:
314: return new CallbackUnresolvedPropertyPrototypeReflection(
315: $property,
316: $property->getDeclaringClass(),
317: false,
318: static fn (Type $type): Type => $type,
319: );
320: }
321:
322: $ancestor = $this->getAncestorWithClassName($property->getDeclaringClass()->getName());
323: $resolvedClassReflection = null;
324: if ($ancestor !== null && $ancestor->hasProperty($propertyName)->yes()) {
325: $resolvedClassReflection = $ancestor->getClassReflection();
326: if ($ancestor !== $this) {
327: $property = $ancestor->getUnresolvedPropertyPrototype($propertyName, $scope)->getNakedProperty();
328: }
329: }
330: if ($resolvedClassReflection === null) {
331: $resolvedClassReflection = $property->getDeclaringClass();
332: }
333:
334: return self::$properties[$description][$propertyName][$canAccessProperty] = new CalledOnTypeUnresolvedPropertyPrototypeReflection(
335: $property,
336: $resolvedClassReflection,
337: true,
338: $this,
339: );
340: }
341:
342: public function hasInstanceProperty(string $propertyName): TrinaryLogic
343: {
344: $classReflection = $this->getClassReflection();
345: if ($classReflection === null) {
346: return TrinaryLogic::createMaybe();
347: }
348:
349: $classHasProperty = RecursionGuard::run($this, static fn (): bool => $classReflection->hasInstanceProperty($propertyName));
350: if ($classHasProperty === true || $classHasProperty instanceof ErrorType) {
351: return TrinaryLogic::createYes();
352: }
353:
354: if ($classReflection->allowsDynamicProperties()) {
355: return TrinaryLogic::createMaybe();
356: }
357:
358: if (!$classReflection->isFinal()) {
359: return TrinaryLogic::createMaybe();
360: }
361:
362: return TrinaryLogic::createNo();
363: }
364:
365: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
366: {
367: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
368: }
369:
370: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
371: {
372: if (!$scope->isInClass()) {
373: $canAccessProperty = 'no';
374: } else {
375: $canAccessProperty = $scope->getClassReflection()->getName();
376: }
377: $description = $this->describeCache();
378:
379: self::touchDescriptionCacheKey($description);
380:
381: if (isset(self::$instanceProperties[$description][$propertyName][$canAccessProperty])) {
382: return self::$instanceProperties[$description][$propertyName][$canAccessProperty];
383: }
384:
385: $nakedClassReflection = $this->getNakedClassReflection();
386: if ($nakedClassReflection === null) {
387: throw new ClassNotFoundException($this->className);
388: }
389:
390: if ($nakedClassReflection->isEnum()) {
391: if (
392: $propertyName === 'name'
393: || ($propertyName === 'value' && $nakedClassReflection->isBackedEnum())
394: ) {
395: $properties = [];
396: foreach ($this->getEnumCases() as $enumCase) {
397: $properties[] = $enumCase->getUnresolvedInstancePropertyPrototype($propertyName, $scope);
398: }
399:
400: if (count($properties) > 0) {
401: if (count($properties) === 1) {
402: return $properties[0];
403: }
404:
405: return new UnionTypeUnresolvedPropertyPrototypeReflection($properties);
406: }
407: }
408: }
409:
410: if (!$nakedClassReflection->hasNativeProperty($propertyName)) {
411: $nakedClassReflection = $this->getClassReflection();
412: }
413:
414: if ($nakedClassReflection === null) {
415: throw new ClassNotFoundException($this->className);
416: }
417:
418: $property = RecursionGuard::run($this, static fn () => $nakedClassReflection->getInstanceProperty($propertyName, $scope));
419: if ($property instanceof ErrorType) {
420: $property = new DummyPropertyReflection($propertyName);
421:
422: return new CallbackUnresolvedPropertyPrototypeReflection(
423: $property,
424: $property->getDeclaringClass(),
425: false,
426: static fn (Type $type): Type => $type,
427: );
428: }
429:
430: $ancestor = $this->getAncestorWithClassName($property->getDeclaringClass()->getName());
431: $resolvedClassReflection = null;
432: if ($ancestor !== null && $ancestor->hasInstanceProperty($propertyName)->yes()) {
433: $resolvedClassReflection = $ancestor->getClassReflection();
434: if ($ancestor !== $this) {
435: $property = $ancestor->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getNakedProperty();
436: }
437: }
438: if ($resolvedClassReflection === null) {
439: $resolvedClassReflection = $property->getDeclaringClass();
440: }
441:
442: return self::$instanceProperties[$description][$propertyName][$canAccessProperty] = new CalledOnTypeUnresolvedPropertyPrototypeReflection(
443: $property,
444: $resolvedClassReflection,
445: true,
446: $this,
447: );
448: }
449:
450: public function hasStaticProperty(string $propertyName): TrinaryLogic
451: {
452: $classReflection = $this->getClassReflection();
453: if ($classReflection === null) {
454: return TrinaryLogic::createMaybe();
455: }
456:
457: $classHasProperty = RecursionGuard::run($this, static fn (): bool => $classReflection->hasStaticProperty($propertyName));
458: if ($classHasProperty === true || $classHasProperty instanceof ErrorType) {
459: return TrinaryLogic::createYes();
460: }
461:
462: if (!$classReflection->isFinal()) {
463: return TrinaryLogic::createMaybe();
464: }
465:
466: return TrinaryLogic::createNo();
467: }
468:
469: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
470: {
471: return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty();
472: }
473:
474: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
475: {
476: if (!$scope->isInClass()) {
477: $canAccessProperty = 'no';
478: } else {
479: $canAccessProperty = $scope->getClassReflection()->getName();
480: }
481: $description = $this->describeCache();
482:
483: self::touchDescriptionCacheKey($description);
484:
485: if (isset(self::$staticProperties[$description][$propertyName][$canAccessProperty])) {
486: return self::$staticProperties[$description][$propertyName][$canAccessProperty];
487: }
488:
489: $nakedClassReflection = $this->getNakedClassReflection();
490: if ($nakedClassReflection === null) {
491: throw new ClassNotFoundException($this->className);
492: }
493:
494: if (!$nakedClassReflection->hasNativeProperty($propertyName)) {
495: $nakedClassReflection = $this->getClassReflection();
496: }
497:
498: if ($nakedClassReflection === null) {
499: throw new ClassNotFoundException($this->className);
500: }
501:
502: $property = RecursionGuard::run($this, static fn () => $nakedClassReflection->getStaticProperty($propertyName));
503: if ($property instanceof ErrorType) {
504: $property = new DummyPropertyReflection($propertyName);
505:
506: return new CallbackUnresolvedPropertyPrototypeReflection(
507: $property,
508: $property->getDeclaringClass(),
509: false,
510: static fn (Type $type): Type => $type,
511: );
512: }
513:
514: $ancestor = $this->getAncestorWithClassName($property->getDeclaringClass()->getName());
515: $resolvedClassReflection = null;
516: if ($ancestor !== null && $ancestor->hasStaticProperty($propertyName)->yes()) {
517: $resolvedClassReflection = $ancestor->getClassReflection();
518: if ($ancestor !== $this) {
519: $property = $ancestor->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getNakedProperty();
520: }
521: }
522: if ($resolvedClassReflection === null) {
523: $resolvedClassReflection = $property->getDeclaringClass();
524: }
525:
526: return self::$staticProperties[$description][$propertyName][$canAccessProperty] = new CalledOnTypeUnresolvedPropertyPrototypeReflection(
527: $property,
528: $resolvedClassReflection,
529: true,
530: $this,
531: );
532: }
533:
534: public function getReferencedClasses(): array
535: {
536: if ($this->className === '') {
537: return [];
538: }
539:
540: return [$this->className];
541: }
542:
543: public function getObjectClassNames(): array
544: {
545: if ($this->className === '') {
546: return [];
547: }
548: return [$this->className];
549: }
550:
551: public function getObjectClassReflections(): array
552: {
553: $classReflection = $this->getClassReflection();
554: if ($classReflection === null) {
555: return [];
556: }
557:
558: return [$classReflection];
559: }
560:
561: public function accepts(Type $type, bool $strictTypes): AcceptsResult
562: {
563: if ($type instanceof StaticType) {
564: return $this->checkSubclassAcceptability($type->getClassName());
565: }
566:
567: if ($type instanceof CompoundType) {
568: return $type->isAcceptedBy($this, $strictTypes);
569: }
570:
571: if ($type instanceof ClosureType) {
572: return new AcceptsResult($this->isInstanceOf(Closure::class), []);
573: }
574:
575: if ($type instanceof ObjectWithoutClassType) {
576: return AcceptsResult::createMaybe();
577: }
578:
579: $thatClassNames = $type->getObjectClassNames();
580: if (count($thatClassNames) > 1) {
581: throw new ShouldNotHappenException();
582: }
583:
584: if ($thatClassNames === []) {
585: return AcceptsResult::createNo();
586: }
587:
588: return $this->checkSubclassAcceptability($thatClassNames[0]);
589: }
590:
591: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
592: {
593: $thatClassNames = $type->getObjectClassNames();
594: if (!$type instanceof CompoundType && $thatClassNames === [] && !$type instanceof ObjectWithoutClassType) {
595: return IsSuperTypeOfResult::createNo();
596: }
597:
598: $thisDescription = $this->describeCache();
599:
600: if ($type instanceof self) {
601: $description = $type->describeCache();
602: } else {
603: $description = $type->describe(VerbosityLevel::cache());
604: }
605:
606: // the call is skipped while the same description is asked about again and again
607: if ($thisDescription !== self::$lastTouchedDescription) {
608: self::touchDescriptionCacheKey($thisDescription);
609: }
610:
611: if (isset(self::$superTypes[$thisDescription][$description])) {
612: return self::$superTypes[$thisDescription][$description];
613: }
614:
615: if ($type instanceof CompoundType) {
616: return self::$superTypes[$thisDescription][$description] = $type->isSubTypeOf($this);
617: }
618:
619: if ($type instanceof ClosureType) {
620: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createFromTrinaryLogic($this->isInstanceOf(Closure::class));
621: }
622:
623: if ($type instanceof ObjectWithoutClassType) {
624: if ($type->getSubtractedType() !== null) {
625: $isSuperType = $type->getSubtractedType()->isSuperTypeOf($this);
626: if ($isSuperType->yes()) {
627: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
628: }
629: }
630: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
631: }
632:
633: $transformResult = static fn (IsSuperTypeOfResult $result) => $result;
634: if ($this->subtractedType !== null) {
635: $isSuperType = $this->subtractedType->isSuperTypeOf($type);
636: if ($isSuperType->yes()) {
637: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
638: }
639: if ($isSuperType->maybe()) {
640: $transformResult = static fn (IsSuperTypeOfResult $result) => $result->and(IsSuperTypeOfResult::createMaybe());
641: }
642: }
643:
644: if (
645: $type instanceof SubtractableType
646: && $type->getSubtractedType() !== null
647: ) {
648: $isSuperType = $type->getSubtractedType()->isSuperTypeOf($this);
649: if ($isSuperType->yes()) {
650: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
651: }
652: }
653:
654: $thisClassName = $this->className;
655: if (count($thatClassNames) > 1) {
656: throw new ShouldNotHappenException();
657: }
658:
659: $thisClassReflection = $this->getClassReflection();
660: $thatClassReflections = $type->getObjectClassReflections();
661: if (count($thatClassReflections) === 1) {
662: $thatClassReflection = $thatClassReflections[0];
663: } else {
664: $thatClassReflection = null;
665: }
666:
667: if ($thisClassReflection === null || $thatClassReflection === null) {
668: if ($thatClassNames[0] === $thisClassName) {
669: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
670: }
671: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
672: }
673:
674: if ($thatClassNames[0] === $thisClassName) {
675: if ($thisClassReflection->getNativeReflection()->isFinal()) {
676: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
677: }
678:
679: if ($thisClassReflection->hasFinalByKeywordOverride()) {
680: if (!$thatClassReflection->hasFinalByKeywordOverride()) {
681: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createMaybe());
682: }
683: }
684:
685: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
686: }
687:
688: if ($thisClassReflection->isTrait() || $thatClassReflection->isTrait()) {
689: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
690: }
691:
692: if ($thisClassReflection->getName() === $thatClassReflection->getName()) {
693: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
694: }
695:
696: if ($thatClassReflection->isSubclassOfClass($thisClassReflection)) {
697: return self::$superTypes[$thisDescription][$description] = $transformResult(IsSuperTypeOfResult::createYes());
698: }
699:
700: if ($thisClassReflection->isSubclassOfClass($thatClassReflection)) {
701: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
702: }
703:
704: if ($thisClassReflection->isInterface() && !$thatClassReflection->isFinalByKeyword()) {
705: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
706: }
707:
708: if ($thatClassReflection->isInterface() && !$thisClassReflection->isFinalByKeyword()) {
709: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createMaybe();
710: }
711:
712: return self::$superTypes[$thisDescription][$description] = IsSuperTypeOfResult::createNo();
713: }
714:
715: public function equals(Type $type): bool
716: {
717: if (get_class($type) !== static::class) {
718: return false;
719: }
720:
721: if ($this->className !== $type->className) {
722: return false;
723: }
724:
725: if ($this->subtractedType === null) {
726: return $type->subtractedType === null;
727: }
728:
729: if ($type->subtractedType === null) {
730: return false;
731: }
732:
733: return $this->subtractedType->equals($type->subtractedType);
734: }
735:
736: private function checkSubclassAcceptability(string $thatClass): AcceptsResult
737: {
738: if ($this->className === $thatClass) {
739: return AcceptsResult::createYes();
740: }
741:
742: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
743:
744: if ($this->getClassReflection() === null || !$reflectionProvider->hasClass($thatClass)) {
745: return AcceptsResult::createNo();
746: }
747:
748: $thisReflection = $this->getClassReflection();
749: $thatReflection = $reflectionProvider->getClass($thatClass);
750:
751: if ($thisReflection->getName() === $thatReflection->getName()) {
752: // class alias
753: return AcceptsResult::createYes();
754: }
755:
756: if ($thisReflection->isInterface() && $thatReflection->isInterface()) {
757: return AcceptsResult::createFromBoolean(
758: $thatReflection->implementsInterface($thisReflection->getName()),
759: );
760: }
761:
762: return AcceptsResult::createFromBoolean(
763: $thatReflection->isSubclassOfClass($thisReflection),
764: );
765: }
766:
767: public function describe(VerbosityLevel $level): string
768: {
769: if ($this->cachedPreciseName !== null && ($level->isValue() || $level->isTypeOnly())) {
770: return $this->cachedPreciseName;
771: }
772:
773: $preciseNameCallback = function (): string {
774: if ($this->cachedPreciseName !== null) {
775: return $this->cachedPreciseName;
776: }
777:
778: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
779: if (!$reflectionProvider->hasClass($this->className)) {
780: return $this->cachedPreciseName = $this->className;
781: }
782:
783: return $this->cachedPreciseName = $reflectionProvider->getClassName($this->className);
784: };
785:
786: $preciseWithSubtracted = fn (): string => $this->className . $this->describeSubtractedType($this->subtractedType, $level);
787:
788: return $level->handle(
789: $preciseNameCallback,
790: $preciseNameCallback,
791: $preciseWithSubtracted,
792: function () use ($preciseWithSubtracted): string {
793: $reflection = $this->classReflection;
794: $line = '';
795: if ($reflection !== null) {
796: $line .= '-';
797: $line .= (string) $reflection->getNativeReflection()->getStartLine();
798: $line .= '-';
799: }
800:
801: return $preciseWithSubtracted() . '-' . static::class . '-' . $line . $this->describeAdditionalCacheKey();
802: },
803: );
804: }
805:
806: protected function describeAdditionalCacheKey(): string
807: {
808: return '';
809: }
810:
811: private function describeCache(): string
812: {
813: if ($this->cachedDescription !== null) {
814: return $this->cachedDescription;
815: }
816:
817: if (static::class !== self::class) {
818: return $this->cachedDescription = $this->describe(VerbosityLevel::cache());
819: }
820:
821: $description = $this->className;
822:
823: if ($this instanceof GenericObjectType) {
824: $description .= '<';
825: $typeDescriptions = [];
826: foreach ($this->getTypes() as $type) {
827: $typeDescriptions[] = $type->describe(VerbosityLevel::cache());
828: }
829: $description .= '<' . implode(', ', $typeDescriptions) . '>';
830: }
831:
832: $description .= $this->describeSubtractedType($this->subtractedType, VerbosityLevel::cache());
833:
834: $reflection = $this->classReflection;
835: if ($reflection !== null) {
836: $description .= '-';
837: $description .= (string) $reflection->getNativeReflection()->getStartLine();
838: $description .= '-';
839:
840: if ($reflection->hasFinalByKeywordOverride()) {
841: $description .= 'f=' . ($reflection->isFinalByKeyword() ? 't' : 'f');
842: }
843: }
844:
845: return $this->cachedDescription = $description;
846: }
847:
848: public function toNumber(): Type
849: {
850: if (
851: $this->isInstanceOf('SimpleXMLElement')->yes()
852: || $this->isInstanceOf('GMP')->yes()
853: ) {
854: return new UnionType([
855: new FloatType(),
856: new IntegerType(),
857: ]);
858: }
859:
860: return new ErrorType();
861: }
862:
863: public function toBitwiseNotType(): Type
864: {
865: return new ErrorType();
866: }
867:
868: public function toGetClassResultType(): Type
869: {
870: return $this->getClassStringType();
871: }
872:
873: public function toClassConstantType(ReflectionProvider $reflectionProvider): Type
874: {
875: if ($reflectionProvider->hasClass($this->className)) {
876: $reflection = $reflectionProvider->getClass($this->className);
877: if ($reflection->isFinalByKeyword()) {
878: return new ConstantStringType($reflection->getName(), true);
879: }
880: }
881:
882: return new IntersectionType([$this->getClassStringType(), new AccessoryLiteralStringType()]);
883: }
884:
885: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
886: {
887: return new ClassNameToObjectTypeResult($this, true);
888: }
889:
890: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
891: {
892: if ($allowString) {
893: return new ClassNameToObjectTypeResult(
894: new UnionType([new ObjectWithoutClassType(), new ClassStringType()]),
895: false,
896: );
897: }
898:
899: return new ClassNameToObjectTypeResult(new ObjectWithoutClassType(), false);
900: }
901:
902: public function toAbsoluteNumber(): Type
903: {
904: return $this->toNumber()->toAbsoluteNumber();
905: }
906:
907: public function toInteger(): Type
908: {
909: if (
910: $this->isInstanceOf('SimpleXMLElement')->yes()
911: || $this->isInstanceOf('GMP')->yes()
912: ) {
913: return new IntegerType();
914: }
915:
916: if (in_array($this->getClassName(), ['CurlHandle', 'CurlMultiHandle'], true)) {
917: return new IntegerType();
918: }
919:
920: return new ErrorType();
921: }
922:
923: public function toFloat(): Type
924: {
925: if (
926: $this->isInstanceOf('SimpleXMLElement')->yes()
927: || $this->isInstanceOf('GMP')->yes()
928: ) {
929: return new FloatType();
930: }
931: return new ErrorType();
932: }
933:
934: public function toString(): Type
935: {
936: if (
937: $this->isInstanceOf('BcMath\Number')->yes()
938: || $this->isInstanceOf('GMP')->yes()
939: ) {
940: return new IntersectionType([
941: new StringType(),
942: new AccessoryNumericStringType(),
943: new AccessoryNonEmptyStringType(),
944: ]);
945: }
946:
947: $classReflection = $this->getClassReflection();
948: if ($classReflection === null) {
949: return new ErrorType();
950: }
951:
952: if ($classReflection->hasNativeMethod('__toString')) {
953: return $this->getMethod('__toString', new OutOfClassScope())->getOnlyVariant()->getReturnType();
954: }
955:
956: return new ErrorType();
957: }
958:
959: public function toArray(): Type
960: {
961: $classReflection = $this->getClassReflection();
962: if ($classReflection === null) {
963: return new ArrayType(new MixedType(), new MixedType());
964: }
965:
966: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
967:
968: if (
969: !$classReflection->getNativeReflection()->isUserDefined()
970: || $classReflection->is(ArrayObject::class)
971: || UniversalObjectCratesClassReflectionExtension::isUniversalObjectCrate(
972: $reflectionProvider,
973: $classReflection,
974: )
975: ) {
976: return new ArrayType(new MixedType(), new MixedType());
977: }
978: $arrayKeys = [];
979: $arrayValues = [];
980:
981: $isFinal = $classReflection->isFinal();
982:
983: do {
984: foreach ($classReflection->getNativeReflection()->getProperties() as $nativeProperty) {
985: if ($nativeProperty->isStatic()) {
986: continue;
987: }
988:
989: $declaringClass = $reflectionProvider->getClass($nativeProperty->getDeclaringClass()->getName());
990: $property = $declaringClass->getNativeProperty($nativeProperty->getName());
991:
992: $keyName = $nativeProperty->getName();
993: if ($nativeProperty->isPrivate()) {
994: $keyName = sprintf(
995: "\0%s\0%s",
996: $declaringClass->getName(),
997: $keyName,
998: );
999: } elseif ($nativeProperty->isProtected()) {
1000: $keyName = sprintf(
1001: "\0*\0%s",
1002: $keyName,
1003: );
1004: }
1005:
1006: $arrayKeys[] = new ConstantStringType($keyName);
1007: $arrayValues[] = $property->getReadableType();
1008: }
1009:
1010: $classReflection = $classReflection->getParentClass();
1011: } while ($classReflection !== null);
1012:
1013: if (!$isFinal) {
1014: if (count($arrayKeys) === 0 || count($arrayKeys) > 16) {
1015: return new ArrayType(new MixedType(), new MixedType());
1016: }
1017:
1018: $types = [new ArrayType(new MixedType(), new MixedType())];
1019: foreach ($arrayKeys as $i => $arrayKey) {
1020: $types[] = new HasOffsetValueType($arrayKey, $arrayValues[$i]);
1021: }
1022:
1023: return new IntersectionType($types);
1024: }
1025:
1026: return new ConstantArrayType($arrayKeys, $arrayValues);
1027: }
1028:
1029: public function toArrayKey(): Type
1030: {
1031: return new ErrorType();
1032: }
1033:
1034: public function toCoercedArgumentType(bool $strictTypes): Type
1035: {
1036: if (!$strictTypes) {
1037: $classReflection = $this->getClassReflection();
1038: if (
1039: $classReflection === null
1040: || !$classReflection->hasNativeMethod('__toString')
1041: ) {
1042: return $this;
1043: }
1044:
1045: return TypeCombinator::union($this, $this->toString());
1046: }
1047:
1048: return $this;
1049: }
1050:
1051: public function toBoolean(): BooleanType
1052: {
1053: if (
1054: $this->isInstanceOf('SimpleXMLElement')->yes()
1055: || $this->isInstanceOf('BcMath\Number')->yes()
1056: || $this->isInstanceOf('GMP')->yes()
1057: ) {
1058: return new BooleanType();
1059: }
1060:
1061: return new ConstantBooleanType(true);
1062: }
1063:
1064: public function isObject(): TrinaryLogic
1065: {
1066: return TrinaryLogic::createYes();
1067: }
1068:
1069: public function getClassStringType(): Type
1070: {
1071: return new GenericClassStringType($this);
1072: }
1073:
1074: public function isEnum(): TrinaryLogic
1075: {
1076: $classReflection = $this->getClassReflection();
1077: if ($classReflection === null) {
1078: return TrinaryLogic::createMaybe();
1079: }
1080:
1081: if (
1082: $classReflection->isEnum()
1083: || $classReflection->is('UnitEnum')
1084: ) {
1085: return TrinaryLogic::createYes();
1086: }
1087:
1088: if (
1089: $classReflection->isInterface()
1090: && !$classReflection->is(Stringable::class) // enums cannot have __toString
1091: && !$classReflection->is(Throwable::class) // enums cannot extend Exception/Error
1092: && !$classReflection->is(DateTimeInterface::class) // userland classes cannot extend DateTimeInterface
1093: ) {
1094: return TrinaryLogic::createMaybe();
1095: }
1096:
1097: return TrinaryLogic::createNo();
1098: }
1099:
1100: public function canAccessProperties(): TrinaryLogic
1101: {
1102: return TrinaryLogic::createYes();
1103: }
1104:
1105: public function canCallMethods(): TrinaryLogic
1106: {
1107: if (strtolower($this->className) === 'stdclass') {
1108: return TrinaryLogic::createNo();
1109: }
1110:
1111: return TrinaryLogic::createYes();
1112: }
1113:
1114: public function hasMethod(string $methodName): TrinaryLogic
1115: {
1116: $classReflection = $this->getClassReflection();
1117: if ($classReflection === null) {
1118: return TrinaryLogic::createMaybe();
1119: }
1120:
1121: if ($classReflection->hasMethod($methodName)) {
1122: return TrinaryLogic::createYes();
1123: }
1124:
1125: if ($classReflection->isFinal()) {
1126: return TrinaryLogic::createNo();
1127: }
1128:
1129: return TrinaryLogic::createMaybe();
1130: }
1131:
1132: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
1133: {
1134: $key = $methodName;
1135: if ($scope->isInClass()) {
1136: $key = sprintf('%s-%s', $key, $scope->getClassReflection()->getCacheKey());
1137: }
1138: return $this->methodCache[$key] ??= $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
1139: }
1140:
1141: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
1142: {
1143: if (!$scope->isInClass()) {
1144: $canCallMethod = 'no';
1145: } else {
1146: $canCallMethod = $scope->getClassReflection()->getName();
1147: }
1148: $description = $this->describeCache();
1149: self::touchDescriptionCacheKey($description);
1150: if (isset(self::$methods[$description][$methodName][$canCallMethod])) {
1151: return self::$methods[$description][$methodName][$canCallMethod];
1152: }
1153:
1154: $nakedClassReflection = $this->getNakedClassReflection();
1155: if ($nakedClassReflection === null) {
1156: throw new ClassNotFoundException($this->className);
1157: }
1158:
1159: if (!$nakedClassReflection->hasNativeMethod($methodName)) {
1160: $nakedClassReflection = $this->getClassReflection();
1161: }
1162:
1163: if ($nakedClassReflection === null) {
1164: throw new ClassNotFoundException($this->className);
1165: }
1166:
1167: $method = $nakedClassReflection->getMethod($methodName, $scope);
1168:
1169: $ancestor = $this->getAncestorWithClassName($method->getDeclaringClass()->getName());
1170: $resolvedClassReflection = null;
1171: if ($ancestor !== null) {
1172: $resolvedClassReflection = $ancestor->getClassReflection();
1173: if ($ancestor !== $this) {
1174: $method = $ancestor->getUnresolvedMethodPrototype($methodName, $scope)->getNakedMethod();
1175: }
1176: }
1177: if ($resolvedClassReflection === null) {
1178: $resolvedClassReflection = $method->getDeclaringClass();
1179: }
1180:
1181: return self::$methods[$description][$methodName][$canCallMethod] = new CalledOnTypeUnresolvedMethodPrototypeReflection(
1182: $method,
1183: $resolvedClassReflection,
1184: true,
1185: $this,
1186: );
1187: }
1188:
1189: public function canAccessConstants(): TrinaryLogic
1190: {
1191: return TrinaryLogic::createYes();
1192: }
1193:
1194: public function hasConstant(string $constantName): TrinaryLogic
1195: {
1196: $classReflection = $this->getClassReflection();
1197: if ($classReflection === null) {
1198: return TrinaryLogic::createMaybe();
1199: }
1200:
1201: if ($classReflection->hasConstant($constantName)) {
1202: return TrinaryLogic::createYes();
1203: }
1204:
1205: if ($classReflection->isFinal()) {
1206: return TrinaryLogic::createNo();
1207: }
1208:
1209: return TrinaryLogic::createMaybe();
1210: }
1211:
1212: public function getConstant(string $constantName): ClassConstantReflection
1213: {
1214: $class = $this->getClassReflection();
1215: if ($class === null) {
1216: throw new ClassNotFoundException($this->className);
1217: }
1218:
1219: return $class->getConstant($constantName);
1220: }
1221:
1222: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
1223: {
1224: $classReflection = $this->getClassReflection();
1225: if ($classReflection === null) {
1226: return new ErrorType();
1227: }
1228:
1229: $ancestorClassReflection = $classReflection->getAncestorWithClassName($ancestorClassName);
1230: if ($ancestorClassReflection === null) {
1231: return new ErrorType();
1232: }
1233:
1234: $activeTemplateTypeMap = $ancestorClassReflection->getPossiblyIncompleteActiveTemplateTypeMap();
1235: $type = $activeTemplateTypeMap->getType($templateTypeName);
1236: if ($type === null) {
1237: return new ErrorType();
1238: }
1239: if ($type instanceof UnresolvedTemplateArgumentType) {
1240: // read out of the object as a derived value - see TemplateTypeHelper::resolveTemplateTypes()
1241: return $type->getDelegate();
1242: }
1243: if ($type instanceof ErrorType) {
1244: $templateTypeMap = $ancestorClassReflection->getTemplateTypeMap();
1245: $templateType = $templateTypeMap->getType($templateTypeName);
1246: if ($templateType === null) {
1247: return $type;
1248: }
1249:
1250: $bound = TemplateTypeHelper::resolveToBounds($templateType);
1251: if ($bound instanceof MixedType && $bound->isExplicitMixed()) {
1252: return new MixedType(false);
1253: }
1254:
1255: return TemplateTypeHelper::resolveToDefaults($templateType);
1256: }
1257:
1258: return $type;
1259: }
1260:
1261: public function getConstantStrings(): array
1262: {
1263: return [];
1264: }
1265:
1266: public function isIterable(): TrinaryLogic
1267: {
1268: return $this->isInstanceOf(Traversable::class);
1269: }
1270:
1271: public function isIterableAtLeastOnce(): TrinaryLogic
1272: {
1273: return $this->isInstanceOf(Traversable::class)
1274: ->and(TrinaryLogic::createMaybe());
1275: }
1276:
1277: public function getArraySize(): Type
1278: {
1279: if ($this->isInstanceOf(Countable::class)->no()) {
1280: return new ErrorType();
1281: }
1282:
1283: if ($this->hasMethod('count')->yes() === false) {
1284: return IntegerRangeType::fromInterval(0, null);
1285: }
1286:
1287: return RecursionGuard::run($this, fn (): Type => $this->getMethod('count', new OutOfClassScope())->getOnlyVariant()->getReturnType());
1288: }
1289:
1290: public function getIterableKeyType(): Type
1291: {
1292: $isTraversable = false;
1293: if ($this->isInstanceOf(IteratorAggregate::class)->yes()) {
1294: $keyType = RecursionGuard::run($this, fn (): Type => $this->getMethod('getIterator', new OutOfClassScope())->getOnlyVariant()->getReturnType()->getIterableKeyType());
1295: $isTraversable = true;
1296: if (!$keyType instanceof MixedType || $keyType->isExplicitMixed()) {
1297: return $keyType;
1298: }
1299: }
1300:
1301: $extraOffsetAccessible = $this->isExtraOffsetAccessibleClass()->yes();
1302: if (!$extraOffsetAccessible && $this->isInstanceOf(Traversable::class)->yes()) {
1303: $isTraversable = true;
1304: $tKey = $this->getTemplateType(Traversable::class, 'TKey');
1305: if (!$tKey instanceof ErrorType) {
1306: if (!$tKey instanceof MixedType || $tKey->isExplicitMixed()) {
1307: return $tKey;
1308: }
1309: }
1310: }
1311:
1312: if ($this->isInstanceOf(Iterator::class)->yes()) {
1313: return RecursionGuard::run($this, fn (): Type => $this->getMethod('key', new OutOfClassScope())->getOnlyVariant()->getReturnType());
1314: }
1315:
1316: if ($extraOffsetAccessible) {
1317: return new MixedType(true);
1318: }
1319:
1320: if ($isTraversable) {
1321: return new MixedType();
1322: }
1323:
1324: return new ErrorType();
1325: }
1326:
1327: public function getFirstIterableKeyType(): Type
1328: {
1329: return $this->getIterableKeyType();
1330: }
1331:
1332: public function getLastIterableKeyType(): Type
1333: {
1334: return $this->getIterableKeyType();
1335: }
1336:
1337: public function getIterableValueType(): Type
1338: {
1339: $isTraversable = false;
1340: if ($this->isInstanceOf(IteratorAggregate::class)->yes()) {
1341: $valueType = RecursionGuard::run($this, fn (): Type => $this->getMethod('getIterator', new OutOfClassScope())->getOnlyVariant()->getReturnType()->getIterableValueType());
1342: $isTraversable = true;
1343: if (!$valueType instanceof MixedType || $valueType->isExplicitMixed()) {
1344: return $valueType;
1345: }
1346: }
1347:
1348: $extraOffsetAccessible = $this->isExtraOffsetAccessibleClass()->yes();
1349: if (!$extraOffsetAccessible && $this->isInstanceOf(Traversable::class)->yes()) {
1350: $isTraversable = true;
1351: $tValue = $this->getTemplateType(Traversable::class, 'TValue');
1352: if (!$tValue instanceof ErrorType) {
1353: if (!$tValue instanceof MixedType || $tValue->isExplicitMixed()) {
1354: return $tValue;
1355: }
1356: }
1357: }
1358:
1359: if ($this->isInstanceOf(Iterator::class)->yes()) {
1360: return RecursionGuard::run($this, fn (): Type => $this->getMethod('current', new OutOfClassScope())->getOnlyVariant()->getReturnType());
1361: }
1362:
1363: if ($extraOffsetAccessible) {
1364: return new MixedType(true);
1365: }
1366:
1367: if ($isTraversable) {
1368: return new MixedType();
1369: }
1370:
1371: return new ErrorType();
1372: }
1373:
1374: public function getFirstIterableValueType(): Type
1375: {
1376: return $this->getIterableValueType();
1377: }
1378:
1379: public function getLastIterableValueType(): Type
1380: {
1381: return $this->getIterableValueType();
1382: }
1383:
1384: public function isNull(): TrinaryLogic
1385: {
1386: return TrinaryLogic::createNo();
1387: }
1388:
1389: public function isConstantValue(): TrinaryLogic
1390: {
1391: return TrinaryLogic::createNo();
1392: }
1393:
1394: public function isConstantScalarValue(): TrinaryLogic
1395: {
1396: return TrinaryLogic::createNo();
1397: }
1398:
1399: public function getConstantScalarTypes(): array
1400: {
1401: return [];
1402: }
1403:
1404: public function getConstantScalarValues(): array
1405: {
1406: return [];
1407: }
1408:
1409: public function isTrue(): TrinaryLogic
1410: {
1411: return TrinaryLogic::createNo();
1412: }
1413:
1414: public function isFalse(): TrinaryLogic
1415: {
1416: return TrinaryLogic::createNo();
1417: }
1418:
1419: public function isBoolean(): TrinaryLogic
1420: {
1421: return TrinaryLogic::createNo();
1422: }
1423:
1424: public function isFloat(): TrinaryLogic
1425: {
1426: return TrinaryLogic::createNo();
1427: }
1428:
1429: public function isInteger(): TrinaryLogic
1430: {
1431: return TrinaryLogic::createNo();
1432: }
1433:
1434: public function isString(): TrinaryLogic
1435: {
1436: return TrinaryLogic::createNo();
1437: }
1438:
1439: public function isNumericString(): TrinaryLogic
1440: {
1441: return TrinaryLogic::createNo();
1442: }
1443:
1444: public function isDecimalIntegerString(): TrinaryLogic
1445: {
1446: return TrinaryLogic::createNo();
1447: }
1448:
1449: public function isNonEmptyString(): TrinaryLogic
1450: {
1451: return TrinaryLogic::createNo();
1452: }
1453:
1454: public function isNonFalsyString(): TrinaryLogic
1455: {
1456: return TrinaryLogic::createNo();
1457: }
1458:
1459: public function isLiteralString(): TrinaryLogic
1460: {
1461: return TrinaryLogic::createNo();
1462: }
1463:
1464: public function isLowercaseString(): TrinaryLogic
1465: {
1466: return TrinaryLogic::createNo();
1467: }
1468:
1469: public function isClassString(): TrinaryLogic
1470: {
1471: return TrinaryLogic::createNo();
1472: }
1473:
1474: public function isUppercaseString(): TrinaryLogic
1475: {
1476: return TrinaryLogic::createNo();
1477: }
1478:
1479: public function getClassStringObjectType(): Type
1480: {
1481: return new ErrorType();
1482: }
1483:
1484: public function getObjectTypeOrClassStringObjectType(): Type
1485: {
1486: return $this;
1487: }
1488:
1489: public function isVoid(): TrinaryLogic
1490: {
1491: return TrinaryLogic::createNo();
1492: }
1493:
1494: public function isScalar(): TrinaryLogic
1495: {
1496: return TrinaryLogic::createNo();
1497: }
1498:
1499: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1500: {
1501: if ($type->isTrue()->yes()) {
1502: return new ConstantBooleanType(true);
1503: }
1504:
1505: return $type->isFalse()->yes()
1506: ? new ConstantBooleanType(false)
1507: : new BooleanType();
1508: }
1509:
1510: private function isExtraOffsetAccessibleClass(): TrinaryLogic
1511: {
1512: $classReflection = $this->getClassReflection();
1513: if ($classReflection === null) {
1514: return TrinaryLogic::createMaybe();
1515: }
1516:
1517: foreach (self::EXTRA_OFFSET_CLASSES as $extraOffsetClass) {
1518: // like $classReflection->is($extraOffsetClass), without looking up the class: the answer
1519: // depends only on the ancestors, and a lookup is recorded as a dependency of the analysed file
1520: $ancestor = $classReflection->getAncestorWithClassName($extraOffsetClass);
1521: if ($ancestor === null) {
1522: continue;
1523: }
1524: if ($ancestor === $classReflection || $classReflection->isSubclassOfClass($ancestor)) {
1525: return TrinaryLogic::createYes();
1526: }
1527: }
1528:
1529: if ($classReflection->isInterface()) {
1530: return TrinaryLogic::createMaybe();
1531: }
1532:
1533: if ($classReflection->isFinal()) {
1534: return TrinaryLogic::createNo();
1535: }
1536:
1537: return TrinaryLogic::createMaybe();
1538: }
1539:
1540: public function isOffsetAccessible(): TrinaryLogic
1541: {
1542: $isArrayAccess = $this->isInstanceOf(ArrayAccess::class);
1543: if ($isArrayAccess->yes()) {
1544: return $isArrayAccess;
1545: }
1546:
1547: return $isArrayAccess->or($this->isExtraOffsetAccessibleClass());
1548: }
1549:
1550: public function isOffsetAccessLegal(): TrinaryLogic
1551: {
1552: return $this->isOffsetAccessible();
1553: }
1554:
1555: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1556: {
1557: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1558: $acceptedOffsetType = RecursionGuard::run($this, function (): Type {
1559: $parameters = $this->getMethod('offsetSet', new OutOfClassScope())->getOnlyVariant()->getParameters();
1560: if (count($parameters) < 2) {
1561: throw new ShouldNotHappenException(sprintf(
1562: 'Method %s::%s() has less than 2 parameters.',
1563: $this->className,
1564: 'offsetSet',
1565: ));
1566: }
1567:
1568: $offsetParameter = $parameters[0];
1569:
1570: return $offsetParameter->getType();
1571: });
1572:
1573: if ($acceptedOffsetType->isSuperTypeOf($offsetType)->no()) {
1574: return TrinaryLogic::createNo();
1575: }
1576:
1577: return TrinaryLogic::createMaybe();
1578: }
1579:
1580: return $this->isExtraOffsetAccessibleClass()
1581: ->and(TrinaryLogic::createMaybe());
1582: }
1583:
1584: public function getOffsetValueType(Type $offsetType): Type
1585: {
1586: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1587: return RecursionGuard::run($this, fn (): Type => $this->getMethod('offsetGet', new OutOfClassScope())->getOnlyVariant()->getReturnType());
1588: }
1589:
1590: if (!$this->isExtraOffsetAccessibleClass()->no()) {
1591: return new MixedType();
1592: }
1593:
1594: return new ErrorType();
1595: }
1596:
1597: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1598: {
1599: if ($this->isOffsetAccessible()->no()) {
1600: return new ErrorType();
1601: }
1602:
1603: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1604: $acceptedValueType = new NeverType();
1605: $acceptedOffsetType = RecursionGuard::run($this, function () use (&$acceptedValueType): Type {
1606: $parameters = $this->getMethod('offsetSet', new OutOfClassScope())->getOnlyVariant()->getParameters();
1607: if (count($parameters) < 2) {
1608: throw new ShouldNotHappenException(sprintf(
1609: 'Method %s::%s() has less than 2 parameters.',
1610: $this->className,
1611: 'offsetSet',
1612: ));
1613: }
1614:
1615: $offsetParameter = $parameters[0];
1616: $acceptedValueType = $parameters[1]->getType();
1617:
1618: return $offsetParameter->getType();
1619: });
1620:
1621: if ($offsetType === null) {
1622: $offsetType = new NullType();
1623: }
1624:
1625: if (
1626: (!$offsetType instanceof MixedType && !$acceptedOffsetType->isSuperTypeOf($offsetType)->yes())
1627: || (!$valueType instanceof MixedType && !$acceptedValueType->isSuperTypeOf($valueType)->yes())
1628: ) {
1629: return new ErrorType();
1630: }
1631: }
1632:
1633: // in the future we may return intersection of $this and OffsetAccessibleType()
1634: return $this;
1635: }
1636:
1637: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1638: {
1639: if ($this->isOffsetAccessible()->no()) {
1640: return new ErrorType();
1641: }
1642:
1643: return $this;
1644: }
1645:
1646: public function unsetOffset(Type $offsetType): Type
1647: {
1648: if ($this->isOffsetAccessible()->no()) {
1649: return new ErrorType();
1650: }
1651:
1652: return $this;
1653: }
1654:
1655: public function getEnumCases(): array
1656: {
1657: $classReflection = $this->getClassReflection();
1658: if ($classReflection === null) {
1659: return [];
1660: }
1661:
1662: if (!$classReflection->isEnum()) {
1663: return [];
1664: }
1665:
1666: $cacheKey = $this->describeCache();
1667: self::touchDescriptionCacheKey($cacheKey);
1668: if (array_key_exists($cacheKey, self::$enumCases)) {
1669: return self::$enumCases[$cacheKey];
1670: }
1671:
1672: $className = $classReflection->getName();
1673:
1674: if ($this->subtractedType !== null) {
1675: $subtractedEnumCaseNames = [];
1676:
1677: foreach ($this->subtractedType->getEnumCases() as $subtractedCase) {
1678: $subtractedEnumCaseNames[$subtractedCase->getEnumCaseName()] = true;
1679: }
1680:
1681: $cases = [];
1682: foreach ($classReflection->getEnumCases() as $enumCase) {
1683: if (array_key_exists($enumCase->getName(), $subtractedEnumCaseNames)) {
1684: continue;
1685: }
1686: $cases[] = new EnumCaseObjectType($className, $enumCase->getName(), $classReflection);
1687: }
1688: } else {
1689: $cases = [];
1690: foreach ($classReflection->getEnumCases() as $enumCase) {
1691: $cases[] = new EnumCaseObjectType($className, $enumCase->getName(), $classReflection);
1692: }
1693: }
1694:
1695: return self::$enumCases[$cacheKey] = $cases;
1696: }
1697:
1698: public function getEnumCaseObject(): ?EnumCaseObjectType
1699: {
1700: $cases = $this->getEnumCases();
1701:
1702: if (count($cases) === 1) {
1703: return $cases[0];
1704: }
1705:
1706: return null;
1707: }
1708:
1709: public function isCallable(): TrinaryLogic
1710: {
1711: $parametersAcceptors = RecursionGuard::run($this, fn () => $this->findCallableParametersAcceptors());
1712: if ($parametersAcceptors === null) {
1713: return TrinaryLogic::createNo();
1714: }
1715: if ($parametersAcceptors instanceof ErrorType) {
1716: return TrinaryLogic::createNo();
1717: }
1718:
1719: if (
1720: count($parametersAcceptors) === 1
1721: && $parametersAcceptors[0] instanceof TrivialParametersAcceptor
1722: ) {
1723: return TrinaryLogic::createMaybe();
1724: }
1725:
1726: return TrinaryLogic::createYes();
1727: }
1728:
1729: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1730: {
1731: if ($this->className === Closure::class) {
1732: return [new TrivialParametersAcceptor('Closure')];
1733: }
1734: $parametersAcceptors = $this->findCallableParametersAcceptors();
1735: if ($parametersAcceptors === null) {
1736: throw new ShouldNotHappenException();
1737: }
1738:
1739: return $parametersAcceptors;
1740: }
1741:
1742: /**
1743: * @return list<CallableParametersAcceptor>|null
1744: */
1745: private function findCallableParametersAcceptors(): ?array
1746: {
1747: $classReflection = $this->getClassReflection();
1748: if ($classReflection === null) {
1749: return [new TrivialParametersAcceptor()];
1750: }
1751:
1752: if ($classReflection->hasNativeMethod('__invoke')) {
1753: $method = $this->getMethod('__invoke', new OutOfClassScope());
1754: return FunctionCallableVariant::createFromVariants(
1755: $method,
1756: $method->getVariants(),
1757: );
1758: }
1759:
1760: if (!$classReflection->isFinalByKeyword()) {
1761: return [new TrivialParametersAcceptor()];
1762: }
1763:
1764: return null;
1765: }
1766:
1767: public function isCloneable(): TrinaryLogic
1768: {
1769: return TrinaryLogic::createYes();
1770: }
1771:
1772: public function isInstanceOf(string $className): TrinaryLogic
1773: {
1774: $classReflection = $this->getClassReflection();
1775: if ($classReflection === null) {
1776: return TrinaryLogic::createMaybe();
1777: }
1778:
1779: if ($classReflection->is($className)) {
1780: return TrinaryLogic::createYes();
1781: }
1782:
1783: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
1784: if ($reflectionProvider->hasClass($className)) {
1785: $thatClassReflection = $reflectionProvider->getClass($className);
1786: if ($thatClassReflection->isFinal()) {
1787: return TrinaryLogic::createNo();
1788: }
1789: }
1790:
1791: if ($classReflection->isInterface()) {
1792: return TrinaryLogic::createMaybe();
1793: }
1794:
1795: return TrinaryLogic::createNo();
1796: }
1797:
1798: public function subtract(Type $type): Type
1799: {
1800: if ($this->subtractedType === null) {
1801: return $this->changeSubtractedType($type);
1802: }
1803:
1804: // A sealed hierarchy rebuilds its subtraction from the flattened parts
1805: // below, so normalising the union of the old and the new subtracted type
1806: // first is wasted work - and quadratic when a removal peels the subtypes
1807: // off one at a time, as removing a whole enum from its own type does.
1808: // Only the path that keeps the subtracted type as it is needs the union.
1809: $matched = $this->matchAllowedSubTypes(array_merge(
1810: TypeUtils::flattenTypes($this->subtractedType),
1811: TypeUtils::flattenTypes($type),
1812: ));
1813: if ($matched !== null) {
1814: return $matched;
1815: }
1816:
1817: return $this->changeSubtractedType(TypeCombinator::union($this->subtractedType, $type));
1818: }
1819:
1820: public function getTypeWithoutSubtractedType(): Type
1821: {
1822: return $this->changeSubtractedType(null);
1823: }
1824:
1825: /**
1826: * Drops the "this is exactly this class" flavour that ClassReflection::asFinal()
1827: * puts on the type of a `new Foo()` expression.
1828: */
1829: public function withoutFinalByKeywordOverride(): Type
1830: {
1831: if ($this->classReflection === null || !$this->classReflection->hasFinalByKeywordOverride()) {
1832: return $this;
1833: }
1834:
1835: return new self(
1836: $this->className,
1837: $this->subtractedType,
1838: $this->classReflection->withoutFinalByKeywordOverride(),
1839: );
1840: }
1841:
1842: public function changeSubtractedType(?Type $subtractedType): Type
1843: {
1844: if ($subtractedType !== null) {
1845: $matched = $this->matchAllowedSubTypes(TypeUtils::flattenTypes($subtractedType));
1846: if ($matched !== null) {
1847: return $matched;
1848: }
1849: }
1850:
1851: if ($this->subtractedType === null && $subtractedType === null) {
1852: return $this;
1853: }
1854:
1855: return new self($this->className, $subtractedType);
1856: }
1857:
1858: /**
1859: * Rebuilds the type from the subtracted members of its sealed hierarchy.
1860: *
1861: * Returns null when the class has no allowed subtypes, or when a subtracted
1862: * type is not one of them - the caller then keeps the subtracted type whole.
1863: *
1864: * @param array<Type> $subtractedTypes flattened, may repeat
1865: */
1866: private function matchAllowedSubTypes(array $subtractedTypes): ?Type
1867: {
1868: $classReflection = $this->getClassReflection();
1869: $allowedSubTypes = $classReflection?->getAllowedSubTypes();
1870: if ($allowedSubTypes === null) {
1871: return null;
1872: }
1873:
1874: $allowedSubTypesCount = count($allowedSubTypes);
1875: $subtractedSubTypes = [];
1876:
1877: // Enum cases are finite values: FiniteTypeSet keys them by value identity, so
1878: // a subtracted case is a lookup instead of an equals() sweep over every
1879: // allowed case - quadratic in the enum size. Allowed subtypes it cannot key
1880: // (a sealed class hierarchy) still take the sweep.
1881: $allowedSet = FiniteTypeSet::create(array_values($allowedSubTypes));
1882: $keyedAllowedSubTypes = $allowedSet !== null ? $allowedSet->getMembers() : [];
1883: $otherAllowedSubTypes = $allowedSet !== null ? $allowedSet->getOthers() : array_values($allowedSubTypes);
1884:
1885: foreach ($subtractedTypes as $subType) {
1886: $key = FiniteTypeSet::key($subType);
1887: if ($key !== null) {
1888: if (!array_key_exists($key, $keyedAllowedSubTypes) || !$subType->equals($keyedAllowedSubTypes[$key])) {
1889: return null;
1890: }
1891:
1892: $subtractedSubTypes[] = $subType;
1893: unset($keyedAllowedSubTypes[$key]);
1894: continue;
1895: }
1896:
1897: foreach ($otherAllowedSubTypes as $i => $allowedSubType) {
1898: if ($subType->equals($allowedSubType)) {
1899: // An allowed subtype is dropped as it matches, so no two matches
1900: // can be the same one and the matches need no keying.
1901: $subtractedSubTypes[] = $subType;
1902: unset($otherAllowedSubTypes[$i]);
1903: continue 2;
1904: }
1905: }
1906:
1907: return null;
1908: }
1909:
1910: $remainingAllowedSubTypes = array_merge(array_values($keyedAllowedSubTypes), array_values($otherAllowedSubTypes));
1911: if (count($remainingAllowedSubTypes) === 1) {
1912: return $remainingAllowedSubTypes[0];
1913: }
1914:
1915: $subtractedSubTypesCount = count($subtractedSubTypes);
1916: if ($subtractedSubTypesCount === $allowedSubTypesCount) {
1917: return new NeverType();
1918: }
1919:
1920: if ($subtractedSubTypesCount === 0) {
1921: return new self($this->className);
1922: }
1923:
1924: if ($subtractedSubTypesCount === 1) {
1925: return new self($this->className, $subtractedSubTypes[0]);
1926: }
1927:
1928: return new self($this->className, new UnionType($subtractedSubTypes));
1929: }
1930:
1931: public function getSubtractedType(): ?Type
1932: {
1933: return $this->subtractedType;
1934: }
1935:
1936: public function traverse(callable $cb): Type
1937: {
1938: $subtractedType = $this->subtractedType !== null ? $cb($this->subtractedType) : null;
1939:
1940: if ($subtractedType !== $this->subtractedType) {
1941: return new self(
1942: $this->className,
1943: $subtractedType,
1944: );
1945: }
1946:
1947: return $this;
1948: }
1949:
1950: public function traverseSimultaneously(Type $right, callable $cb): Type
1951: {
1952: if ($this->subtractedType === null) {
1953: return $this;
1954: }
1955:
1956: return new self($this->className);
1957: }
1958:
1959: public function getNakedClassReflection(): ?ClassReflection
1960: {
1961: $classReflection = $this->resolvedClassReflection();
1962: if ($classReflection !== null) {
1963: return $classReflection;
1964: }
1965:
1966: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
1967: if (!$reflectionProvider->hasClass($this->className)) {
1968: return null;
1969: }
1970:
1971: return $reflectionProvider->getClass($this->className);
1972: }
1973:
1974: public function getClassReflection(): ?ClassReflection
1975: {
1976: if ($this->returnedClassReflection !== null) {
1977: return $this->returnedClassReflection;
1978: }
1979:
1980: $classReflection = $this->classReflection ?? $this->lazyClassReflection;
1981: if ($classReflection === null) {
1982: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
1983: if (!$reflectionProvider->hasClass($this->className)) {
1984: return null;
1985: }
1986:
1987: $classReflection = $this->lazyClassReflection = $reflectionProvider->getClass($this->className);
1988: }
1989:
1990: if ($classReflection->isGeneric()) {
1991: return $this->returnedClassReflection = $classReflection->withTypes(array_values($classReflection->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()));
1992: }
1993:
1994: return $this->returnedClassReflection = $classReflection;
1995: }
1996:
1997: /** The reflection already known, from either source — never triggers a fetch. */
1998: private function resolvedClassReflection(): ?ClassReflection
1999: {
2000: return $this->classReflection ?? $this->lazyClassReflection;
2001: }
2002:
2003: public function getAncestorWithClassName(string $className): ?self
2004: {
2005: if ($this->className === $className) {
2006: return $this;
2007: }
2008:
2009: $resolvedClassReflection = $this->resolvedClassReflection();
2010: if ($resolvedClassReflection !== null && $className === $resolvedClassReflection->getName()) {
2011: return $this;
2012: }
2013:
2014: if (array_key_exists($className, $this->currentAncestors)) {
2015: return $this->currentAncestors[$className];
2016: }
2017:
2018: $description = $this->describeCache();
2019: self::touchDescriptionCacheKey($description);
2020: if (
2021: array_key_exists($description, self::$ancestors)
2022: && array_key_exists($className, self::$ancestors[$description])
2023: ) {
2024: return self::$ancestors[$description][$className];
2025: }
2026:
2027: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
2028: if (!$reflectionProvider->hasClass($className)) {
2029: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2030: }
2031: $theirReflection = $reflectionProvider->getClass($className);
2032:
2033: $thisReflection = $this->getClassReflection();
2034: if ($thisReflection === null) {
2035: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2036: }
2037: if ($theirReflection->getName() === $thisReflection->getName()) {
2038: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $this;
2039: }
2040:
2041: foreach ($this->getInterfaces() as $interface) {
2042: $ancestor = $interface->getAncestorWithClassName($className);
2043: if ($ancestor !== null) {
2044: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $ancestor;
2045: }
2046: }
2047:
2048: $parent = $this->getParent();
2049: if ($parent !== null) {
2050: $ancestor = $parent->getAncestorWithClassName($className);
2051: if ($ancestor !== null) {
2052: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $ancestor;
2053: }
2054: }
2055:
2056: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2057: }
2058:
2059: private function getParent(): ?ObjectType
2060: {
2061: if ($this->cachedParent !== null) {
2062: return $this->cachedParent;
2063: }
2064: $thisReflection = $this->getClassReflection();
2065: if ($thisReflection === null) {
2066: return null;
2067: }
2068:
2069: $parentReflection = $thisReflection->getParentClass();
2070: if ($parentReflection === null) {
2071: return null;
2072: }
2073:
2074: return $this->cachedParent = $parentReflection->getObjectType();
2075: }
2076:
2077: /** @return ObjectType[] */
2078: private function getInterfaces(): array
2079: {
2080: if ($this->cachedInterfaces !== null) {
2081: return $this->cachedInterfaces;
2082: }
2083: $thisReflection = $this->getClassReflection();
2084: if ($thisReflection === null) {
2085: return $this->cachedInterfaces = [];
2086: }
2087:
2088: return $this->cachedInterfaces = array_map(static fn (ClassReflection $interfaceReflection): self => $interfaceReflection->getObjectType(), $thisReflection->getInterfaces());
2089: }
2090:
2091: public function tryRemove(Type $typeToRemove): ?Type
2092: {
2093: if ($typeToRemove instanceof ObjectType) {
2094: foreach (UnionType::EQUAL_UNION_CLASSES as $baseClass => $classes) {
2095: if ($this->getClassName() !== $baseClass) {
2096: continue;
2097: }
2098:
2099: foreach ($classes as $index => $class) {
2100: if ($typeToRemove->getClassName() === $class) {
2101: unset($classes[$index]);
2102:
2103: return TypeCombinator::union(
2104: ...array_map(static fn (string $objectClass): Type => new ObjectType($objectClass), $classes),
2105: );
2106: }
2107: }
2108: }
2109: }
2110:
2111: if ($this->isSuperTypeOf($typeToRemove)->yes()) {
2112: return $this->subtract($typeToRemove);
2113: }
2114:
2115: $classReflection = $this->getClassReflection();
2116: if ($typeToRemove instanceof UnionType && $classReflection !== null && $classReflection->getAllowedSubTypes() !== null) {
2117: // A sealed hierarchy subtracts by set difference, so the members this
2118: // type no longer holds (already subtracted) are no-ops and the rest come
2119: // off in one subtraction - the same result as removing them one at a
2120: // time, without rebuilding the subtracted union once per member.
2121: $membersToRemove = [];
2122: foreach ($typeToRemove->getTypes() as $member) {
2123: if ($member->isSuperTypeOf($this)->yes()) {
2124: return new NeverType();
2125: }
2126:
2127: $isSuperTypeOfMember = $this->isSuperTypeOf($member);
2128: if ($isSuperTypeOfMember->yes()) {
2129: $membersToRemove[] = $member;
2130: continue;
2131: }
2132: if ($isSuperTypeOfMember->maybe()) {
2133: return null;
2134: }
2135: }
2136:
2137: if ($membersToRemove === []) {
2138: return $this;
2139: }
2140:
2141: return $this->subtract(count($membersToRemove) === 1 ? $membersToRemove[0] : new UnionType($membersToRemove));
2142: }
2143:
2144: return null;
2145: }
2146:
2147: public function getFiniteTypes(): array
2148: {
2149: return $this->getEnumCases();
2150: }
2151:
2152: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
2153: {
2154: $object = new ObjectWithoutClassType();
2155: if (!$exponent instanceof NeverType && !$object->isSuperTypeOf($this)->no() && !$object->isSuperTypeOf($exponent)->no()) {
2156: return TypeCombinator::union($this, $exponent);
2157: }
2158: return new ErrorType();
2159: }
2160:
2161: public function toPhpDocNode(): TypeNode
2162: {
2163: return new FullyQualifiedNameNode($this->getClassName());
2164: }
2165:
2166: public function toNativePhpTypeNode(NativeTypePosition $position)
2167: {
2168: $className = $this->getClassName();
2169: if ($className === '' || !$position->isClassNameAllowed()) {
2170: return null;
2171: }
2172:
2173: return new FullyQualified($className);
2174: }
2175:
2176: public function hasTemplateOrLateResolvableType(): bool
2177: {
2178: if ($this->subtractedType === null) {
2179: return false;
2180: }
2181:
2182: return $this->subtractedType->hasTemplateOrLateResolvableType();
2183: }
2184:
2185: public function toValueSet(): ValueSet
2186: {
2187: return ValueSet::createObjects($this);
2188: }
2189:
2190: }
2191: