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 getKindMask(): int
1385: {
1386: return TypeKind::OBJECT;
1387: }
1388:
1389: public function isNull(): TrinaryLogic
1390: {
1391: return TrinaryLogic::createNo();
1392: }
1393:
1394: public function isConstantValue(): TrinaryLogic
1395: {
1396: return TrinaryLogic::createNo();
1397: }
1398:
1399: public function isConstantScalarValue(): TrinaryLogic
1400: {
1401: return TrinaryLogic::createNo();
1402: }
1403:
1404: public function getConstantScalarTypes(): array
1405: {
1406: return [];
1407: }
1408:
1409: public function getConstantScalarValues(): array
1410: {
1411: return [];
1412: }
1413:
1414: public function isTrue(): TrinaryLogic
1415: {
1416: return TrinaryLogic::createNo();
1417: }
1418:
1419: public function isFalse(): TrinaryLogic
1420: {
1421: return TrinaryLogic::createNo();
1422: }
1423:
1424: public function isBoolean(): TrinaryLogic
1425: {
1426: return TrinaryLogic::createNo();
1427: }
1428:
1429: public function isFloat(): TrinaryLogic
1430: {
1431: return TrinaryLogic::createNo();
1432: }
1433:
1434: public function isInteger(): TrinaryLogic
1435: {
1436: return TrinaryLogic::createNo();
1437: }
1438:
1439: public function isString(): TrinaryLogic
1440: {
1441: return TrinaryLogic::createNo();
1442: }
1443:
1444: public function isNumericString(): TrinaryLogic
1445: {
1446: return TrinaryLogic::createNo();
1447: }
1448:
1449: public function isDecimalIntegerString(): TrinaryLogic
1450: {
1451: return TrinaryLogic::createNo();
1452: }
1453:
1454: public function isNonEmptyString(): TrinaryLogic
1455: {
1456: return TrinaryLogic::createNo();
1457: }
1458:
1459: public function isNonFalsyString(): TrinaryLogic
1460: {
1461: return TrinaryLogic::createNo();
1462: }
1463:
1464: public function isLiteralString(): TrinaryLogic
1465: {
1466: return TrinaryLogic::createNo();
1467: }
1468:
1469: public function getStringRefinement(): ?int
1470: {
1471: return null;
1472: }
1473:
1474: public function isLowercaseString(): TrinaryLogic
1475: {
1476: return TrinaryLogic::createNo();
1477: }
1478:
1479: public function isClassString(): TrinaryLogic
1480: {
1481: return TrinaryLogic::createNo();
1482: }
1483:
1484: public function isUppercaseString(): TrinaryLogic
1485: {
1486: return TrinaryLogic::createNo();
1487: }
1488:
1489: public function getClassStringObjectType(): Type
1490: {
1491: return new ErrorType();
1492: }
1493:
1494: public function getObjectTypeOrClassStringObjectType(): Type
1495: {
1496: return $this;
1497: }
1498:
1499: public function isVoid(): TrinaryLogic
1500: {
1501: return TrinaryLogic::createNo();
1502: }
1503:
1504: public function isScalar(): TrinaryLogic
1505: {
1506: return TrinaryLogic::createNo();
1507: }
1508:
1509: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1510: {
1511: if ($type->isTrue()->yes()) {
1512: return new ConstantBooleanType(true);
1513: }
1514:
1515: return $type->isFalse()->yes()
1516: ? new ConstantBooleanType(false)
1517: : new BooleanType();
1518: }
1519:
1520: private function isExtraOffsetAccessibleClass(): TrinaryLogic
1521: {
1522: $classReflection = $this->getClassReflection();
1523: if ($classReflection === null) {
1524: return TrinaryLogic::createMaybe();
1525: }
1526:
1527: foreach (self::EXTRA_OFFSET_CLASSES as $extraOffsetClass) {
1528: // like $classReflection->is($extraOffsetClass), without looking up the class: the answer
1529: // depends only on the ancestors, and a lookup is recorded as a dependency of the analysed file
1530: $ancestor = $classReflection->getAncestorWithClassName($extraOffsetClass);
1531: if ($ancestor === null) {
1532: continue;
1533: }
1534: if ($ancestor === $classReflection || $classReflection->isSubclassOfClass($ancestor)) {
1535: return TrinaryLogic::createYes();
1536: }
1537: }
1538:
1539: if ($classReflection->isInterface()) {
1540: return TrinaryLogic::createMaybe();
1541: }
1542:
1543: if ($classReflection->isFinal()) {
1544: return TrinaryLogic::createNo();
1545: }
1546:
1547: return TrinaryLogic::createMaybe();
1548: }
1549:
1550: public function isOffsetAccessible(): TrinaryLogic
1551: {
1552: $isArrayAccess = $this->isInstanceOf(ArrayAccess::class);
1553: if ($isArrayAccess->yes()) {
1554: return $isArrayAccess;
1555: }
1556:
1557: return $isArrayAccess->or($this->isExtraOffsetAccessibleClass());
1558: }
1559:
1560: public function isOffsetAccessLegal(): TrinaryLogic
1561: {
1562: return $this->isOffsetAccessible();
1563: }
1564:
1565: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1566: {
1567: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1568: $acceptedOffsetType = RecursionGuard::run($this, function (): Type {
1569: $parameters = $this->getMethod('offsetSet', new OutOfClassScope())->getOnlyVariant()->getParameters();
1570: if (count($parameters) < 2) {
1571: throw new ShouldNotHappenException(sprintf(
1572: 'Method %s::%s() has less than 2 parameters.',
1573: $this->className,
1574: 'offsetSet',
1575: ));
1576: }
1577:
1578: $offsetParameter = $parameters[0];
1579:
1580: return $offsetParameter->getType();
1581: });
1582:
1583: if ($acceptedOffsetType->isSuperTypeOf($offsetType)->no()) {
1584: return TrinaryLogic::createNo();
1585: }
1586:
1587: return TrinaryLogic::createMaybe();
1588: }
1589:
1590: return $this->isExtraOffsetAccessibleClass()
1591: ->and(TrinaryLogic::createMaybe());
1592: }
1593:
1594: public function getOffsetValueType(Type $offsetType): Type
1595: {
1596: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1597: return RecursionGuard::run($this, fn (): Type => $this->getMethod('offsetGet', new OutOfClassScope())->getOnlyVariant()->getReturnType());
1598: }
1599:
1600: if (!$this->isExtraOffsetAccessibleClass()->no()) {
1601: return new MixedType();
1602: }
1603:
1604: return new ErrorType();
1605: }
1606:
1607: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1608: {
1609: if ($this->isOffsetAccessible()->no()) {
1610: return new ErrorType();
1611: }
1612:
1613: if ($this->isInstanceOf(ArrayAccess::class)->yes()) {
1614: $acceptedValueType = new NeverType();
1615: $acceptedOffsetType = RecursionGuard::run($this, function () use (&$acceptedValueType): Type {
1616: $parameters = $this->getMethod('offsetSet', new OutOfClassScope())->getOnlyVariant()->getParameters();
1617: if (count($parameters) < 2) {
1618: throw new ShouldNotHappenException(sprintf(
1619: 'Method %s::%s() has less than 2 parameters.',
1620: $this->className,
1621: 'offsetSet',
1622: ));
1623: }
1624:
1625: $offsetParameter = $parameters[0];
1626: $acceptedValueType = $parameters[1]->getType();
1627:
1628: return $offsetParameter->getType();
1629: });
1630:
1631: if ($offsetType === null) {
1632: $offsetType = new NullType();
1633: }
1634:
1635: if (
1636: (!$offsetType instanceof MixedType && !$acceptedOffsetType->isSuperTypeOf($offsetType)->yes())
1637: || (!$valueType instanceof MixedType && !$acceptedValueType->isSuperTypeOf($valueType)->yes())
1638: ) {
1639: return new ErrorType();
1640: }
1641: }
1642:
1643: // in the future we may return intersection of $this and OffsetAccessibleType()
1644: return $this;
1645: }
1646:
1647: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1648: {
1649: if ($this->isOffsetAccessible()->no()) {
1650: return new ErrorType();
1651: }
1652:
1653: return $this;
1654: }
1655:
1656: public function unsetOffset(Type $offsetType): Type
1657: {
1658: if ($this->isOffsetAccessible()->no()) {
1659: return new ErrorType();
1660: }
1661:
1662: return $this;
1663: }
1664:
1665: public function getEnumCases(): array
1666: {
1667: $classReflection = $this->getClassReflection();
1668: if ($classReflection === null) {
1669: return [];
1670: }
1671:
1672: if (!$classReflection->isEnum()) {
1673: return [];
1674: }
1675:
1676: $cacheKey = $this->describeCache();
1677: self::touchDescriptionCacheKey($cacheKey);
1678: if (array_key_exists($cacheKey, self::$enumCases)) {
1679: return self::$enumCases[$cacheKey];
1680: }
1681:
1682: $className = $classReflection->getName();
1683:
1684: if ($this->subtractedType !== null) {
1685: $subtractedEnumCaseNames = [];
1686:
1687: foreach ($this->subtractedType->getEnumCases() as $subtractedCase) {
1688: $subtractedEnumCaseNames[$subtractedCase->getEnumCaseName()] = true;
1689: }
1690:
1691: $cases = [];
1692: foreach ($classReflection->getEnumCases() as $enumCase) {
1693: if (array_key_exists($enumCase->getName(), $subtractedEnumCaseNames)) {
1694: continue;
1695: }
1696: $cases[] = new EnumCaseObjectType($className, $enumCase->getName(), $classReflection);
1697: }
1698: } else {
1699: $cases = [];
1700: foreach ($classReflection->getEnumCases() as $enumCase) {
1701: $cases[] = new EnumCaseObjectType($className, $enumCase->getName(), $classReflection);
1702: }
1703: }
1704:
1705: return self::$enumCases[$cacheKey] = $cases;
1706: }
1707:
1708: public function getEnumCaseObject(): ?EnumCaseObjectType
1709: {
1710: $cases = $this->getEnumCases();
1711:
1712: if (count($cases) === 1) {
1713: return $cases[0];
1714: }
1715:
1716: return null;
1717: }
1718:
1719: public function isCallable(): TrinaryLogic
1720: {
1721: $parametersAcceptors = RecursionGuard::run($this, fn () => $this->findCallableParametersAcceptors());
1722: if ($parametersAcceptors === null) {
1723: return TrinaryLogic::createNo();
1724: }
1725: if ($parametersAcceptors instanceof ErrorType) {
1726: return TrinaryLogic::createNo();
1727: }
1728:
1729: if (
1730: count($parametersAcceptors) === 1
1731: && $parametersAcceptors[0] instanceof TrivialParametersAcceptor
1732: ) {
1733: return TrinaryLogic::createMaybe();
1734: }
1735:
1736: return TrinaryLogic::createYes();
1737: }
1738:
1739: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1740: {
1741: if ($this->className === Closure::class) {
1742: return [new TrivialParametersAcceptor('Closure')];
1743: }
1744: $parametersAcceptors = $this->findCallableParametersAcceptors();
1745: if ($parametersAcceptors === null) {
1746: throw new ShouldNotHappenException();
1747: }
1748:
1749: return $parametersAcceptors;
1750: }
1751:
1752: /**
1753: * @return list<CallableParametersAcceptor>|null
1754: */
1755: private function findCallableParametersAcceptors(): ?array
1756: {
1757: $classReflection = $this->getClassReflection();
1758: if ($classReflection === null) {
1759: return [new TrivialParametersAcceptor()];
1760: }
1761:
1762: if ($classReflection->hasNativeMethod('__invoke')) {
1763: $method = $this->getMethod('__invoke', new OutOfClassScope());
1764: return FunctionCallableVariant::createFromVariants(
1765: $method,
1766: $method->getVariants(),
1767: );
1768: }
1769:
1770: if (!$classReflection->isFinalByKeyword()) {
1771: return [new TrivialParametersAcceptor()];
1772: }
1773:
1774: return null;
1775: }
1776:
1777: public function isCloneable(): TrinaryLogic
1778: {
1779: return TrinaryLogic::createYes();
1780: }
1781:
1782: public function isInstanceOf(string $className): TrinaryLogic
1783: {
1784: $classReflection = $this->getClassReflection();
1785: if ($classReflection === null) {
1786: return TrinaryLogic::createMaybe();
1787: }
1788:
1789: if ($classReflection->is($className)) {
1790: return TrinaryLogic::createYes();
1791: }
1792:
1793: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
1794: if ($reflectionProvider->hasClass($className)) {
1795: $thatClassReflection = $reflectionProvider->getClass($className);
1796: // an instance of a subclass of this class may be one
1797: if ($thatClassReflection->isSubclassOfClass($classReflection)) {
1798: return TrinaryLogic::createMaybe();
1799: }
1800: if ($thatClassReflection->isFinal()) {
1801: return TrinaryLogic::createNo();
1802: }
1803: // a subclass of a non-final class may implement the interface (as isSuperTypeOf() says)
1804: if ($thatClassReflection->isInterface() && !$classReflection->isFinalByKeyword()) {
1805: return TrinaryLogic::createMaybe();
1806: }
1807: }
1808:
1809: if ($classReflection->isInterface()) {
1810: return TrinaryLogic::createMaybe();
1811: }
1812:
1813: return TrinaryLogic::createNo();
1814: }
1815:
1816: public function subtract(Type $type): Type
1817: {
1818: if ($this->subtractedType === null) {
1819: return $this->changeSubtractedType($type);
1820: }
1821:
1822: // A sealed hierarchy rebuilds its subtraction from the flattened parts
1823: // below, so normalising the union of the old and the new subtracted type
1824: // first is wasted work - and quadratic when a removal peels the subtypes
1825: // off one at a time, as removing a whole enum from its own type does.
1826: // Only the path that keeps the subtracted type as it is needs the union.
1827: $matched = $this->matchAllowedSubTypes(array_merge(
1828: TypeUtils::flattenTypes($this->subtractedType),
1829: TypeUtils::flattenTypes($type),
1830: ));
1831: if ($matched !== null) {
1832: return $matched;
1833: }
1834:
1835: return $this->changeSubtractedType(TypeCombinator::union($this->subtractedType, $type));
1836: }
1837:
1838: public function getTypeWithoutSubtractedType(): Type
1839: {
1840: return $this->changeSubtractedType(null);
1841: }
1842:
1843: /**
1844: * Drops the "this is exactly this class" flavour that ClassReflection::asFinal()
1845: * puts on the type of a `new Foo()` expression.
1846: */
1847: public function withoutFinalByKeywordOverride(): Type
1848: {
1849: if ($this->classReflection === null || !$this->classReflection->hasFinalByKeywordOverride()) {
1850: return $this;
1851: }
1852:
1853: return new self(
1854: $this->className,
1855: $this->subtractedType,
1856: $this->classReflection->withoutFinalByKeywordOverride(),
1857: );
1858: }
1859:
1860: public function changeSubtractedType(?Type $subtractedType): Type
1861: {
1862: if ($subtractedType !== null) {
1863: $matched = $this->matchAllowedSubTypes(TypeUtils::flattenTypes($subtractedType));
1864: if ($matched !== null) {
1865: return $matched;
1866: }
1867: }
1868:
1869: if ($this->subtractedType === null && $subtractedType === null) {
1870: return $this;
1871: }
1872:
1873: return new self($this->className, $subtractedType);
1874: }
1875:
1876: /**
1877: * Rebuilds the type from the subtracted members of its sealed hierarchy.
1878: *
1879: * Returns null when the class has no allowed subtypes, or when a subtracted
1880: * type is not one of them - the caller then keeps the subtracted type whole.
1881: *
1882: * @param array<Type> $subtractedTypes flattened, may repeat
1883: */
1884: private function matchAllowedSubTypes(array $subtractedTypes): ?Type
1885: {
1886: $classReflection = $this->getClassReflection();
1887: $allowedSubTypes = $classReflection?->getAllowedSubTypes();
1888: if ($allowedSubTypes === null) {
1889: return null;
1890: }
1891:
1892: $allowedSubTypesCount = count($allowedSubTypes);
1893: $subtractedSubTypes = [];
1894:
1895: // Enum cases are finite values: FiniteTypeSet keys them by value identity, so
1896: // a subtracted case is a lookup instead of an equals() sweep over every
1897: // allowed case - quadratic in the enum size. Allowed subtypes it cannot key
1898: // (a sealed class hierarchy) still take the sweep.
1899: $allowedSet = FiniteTypeSet::create(array_values($allowedSubTypes));
1900: $keyedAllowedSubTypes = $allowedSet !== null ? $allowedSet->getMembers() : [];
1901: $otherAllowedSubTypes = $allowedSet !== null ? $allowedSet->getOthers() : array_values($allowedSubTypes);
1902:
1903: foreach ($subtractedTypes as $subType) {
1904: $key = FiniteTypeSet::key($subType);
1905: if ($key !== null) {
1906: if (!array_key_exists($key, $keyedAllowedSubTypes) || !$subType->equals($keyedAllowedSubTypes[$key])) {
1907: return null;
1908: }
1909:
1910: $subtractedSubTypes[] = $subType;
1911: unset($keyedAllowedSubTypes[$key]);
1912: continue;
1913: }
1914:
1915: foreach ($otherAllowedSubTypes as $i => $allowedSubType) {
1916: if ($subType->equals($allowedSubType)) {
1917: // An allowed subtype is dropped as it matches, so no two matches
1918: // can be the same one and the matches need no keying.
1919: $subtractedSubTypes[] = $subType;
1920: unset($otherAllowedSubTypes[$i]);
1921: continue 2;
1922: }
1923: }
1924:
1925: return null;
1926: }
1927:
1928: $remainingAllowedSubTypes = array_merge(array_values($keyedAllowedSubTypes), array_values($otherAllowedSubTypes));
1929: if (count($remainingAllowedSubTypes) === 1) {
1930: return $remainingAllowedSubTypes[0];
1931: }
1932:
1933: $subtractedSubTypesCount = count($subtractedSubTypes);
1934: if ($subtractedSubTypesCount === $allowedSubTypesCount) {
1935: return new NeverType();
1936: }
1937:
1938: if ($subtractedSubTypesCount === 0) {
1939: return new self($this->className);
1940: }
1941:
1942: if ($subtractedSubTypesCount === 1) {
1943: return new self($this->className, $subtractedSubTypes[0]);
1944: }
1945:
1946: return new self($this->className, new UnionType($subtractedSubTypes));
1947: }
1948:
1949: public function getSubtractedType(): ?Type
1950: {
1951: return $this->subtractedType;
1952: }
1953:
1954: public function traverse(callable $cb): Type
1955: {
1956: $subtractedType = $this->subtractedType !== null ? $cb($this->subtractedType) : null;
1957:
1958: if ($subtractedType !== $this->subtractedType) {
1959: return new self(
1960: $this->className,
1961: $subtractedType,
1962: );
1963: }
1964:
1965: return $this;
1966: }
1967:
1968: public function traverseSimultaneously(Type $right, callable $cb): Type
1969: {
1970: if ($this->subtractedType === null) {
1971: return $this;
1972: }
1973:
1974: return new self($this->className);
1975: }
1976:
1977: public function getNakedClassReflection(): ?ClassReflection
1978: {
1979: $classReflection = $this->resolvedClassReflection();
1980: if ($classReflection !== null) {
1981: return $classReflection;
1982: }
1983:
1984: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
1985: if (!$reflectionProvider->hasClass($this->className)) {
1986: return null;
1987: }
1988:
1989: return $reflectionProvider->getClass($this->className);
1990: }
1991:
1992: public function getClassReflection(): ?ClassReflection
1993: {
1994: if ($this->returnedClassReflection !== null) {
1995: return $this->returnedClassReflection;
1996: }
1997:
1998: $classReflection = $this->classReflection ?? $this->lazyClassReflection;
1999: if ($classReflection === null) {
2000: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
2001: if (!$reflectionProvider->hasClass($this->className)) {
2002: return null;
2003: }
2004:
2005: $classReflection = $this->lazyClassReflection = $reflectionProvider->getClass($this->className);
2006: }
2007:
2008: if ($classReflection->isGeneric()) {
2009: return $this->returnedClassReflection = $classReflection->withTypes(array_values($classReflection->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()));
2010: }
2011:
2012: return $this->returnedClassReflection = $classReflection;
2013: }
2014:
2015: /** The reflection already known, from either source — never triggers a fetch. */
2016: private function resolvedClassReflection(): ?ClassReflection
2017: {
2018: return $this->classReflection ?? $this->lazyClassReflection;
2019: }
2020:
2021: public function getAncestorWithClassName(string $className): ?self
2022: {
2023: if ($this->className === $className) {
2024: return $this;
2025: }
2026:
2027: $resolvedClassReflection = $this->resolvedClassReflection();
2028: if ($resolvedClassReflection !== null && $className === $resolvedClassReflection->getName()) {
2029: return $this;
2030: }
2031:
2032: if (array_key_exists($className, $this->currentAncestors)) {
2033: return $this->currentAncestors[$className];
2034: }
2035:
2036: $description = $this->describeCache();
2037: self::touchDescriptionCacheKey($description);
2038: if (
2039: array_key_exists($description, self::$ancestors)
2040: && array_key_exists($className, self::$ancestors[$description])
2041: ) {
2042: return self::$ancestors[$description][$className];
2043: }
2044:
2045: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
2046: if (!$reflectionProvider->hasClass($className)) {
2047: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2048: }
2049: $theirReflection = $reflectionProvider->getClass($className);
2050:
2051: $thisReflection = $this->getClassReflection();
2052: if ($thisReflection === null) {
2053: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2054: }
2055: if ($theirReflection->getName() === $thisReflection->getName()) {
2056: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $this;
2057: }
2058:
2059: foreach ($this->getInterfaces() as $interface) {
2060: $ancestor = $interface->getAncestorWithClassName($className);
2061: if ($ancestor !== null) {
2062: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $ancestor;
2063: }
2064: }
2065:
2066: $parent = $this->getParent();
2067: if ($parent !== null) {
2068: $ancestor = $parent->getAncestorWithClassName($className);
2069: if ($ancestor !== null) {
2070: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = $ancestor;
2071: }
2072: }
2073:
2074: return self::$ancestors[$description][$className] = $this->currentAncestors[$className] = null;
2075: }
2076:
2077: private function getParent(): ?ObjectType
2078: {
2079: if ($this->cachedParent !== null) {
2080: return $this->cachedParent;
2081: }
2082: $thisReflection = $this->getClassReflection();
2083: if ($thisReflection === null) {
2084: return null;
2085: }
2086:
2087: $parentReflection = $thisReflection->getParentClass();
2088: if ($parentReflection === null) {
2089: return null;
2090: }
2091:
2092: return $this->cachedParent = $parentReflection->getObjectType();
2093: }
2094:
2095: /** @return ObjectType[] */
2096: private function getInterfaces(): array
2097: {
2098: if ($this->cachedInterfaces !== null) {
2099: return $this->cachedInterfaces;
2100: }
2101: $thisReflection = $this->getClassReflection();
2102: if ($thisReflection === null) {
2103: return $this->cachedInterfaces = [];
2104: }
2105:
2106: return $this->cachedInterfaces = array_map(static fn (ClassReflection $interfaceReflection): self => $interfaceReflection->getObjectType(), $thisReflection->getInterfaces());
2107: }
2108:
2109: public function tryRemove(Type $typeToRemove): ?Type
2110: {
2111: if ($typeToRemove instanceof ObjectType) {
2112: foreach (UnionType::EQUAL_UNION_CLASSES as $baseClass => $classes) {
2113: if ($this->getClassName() !== $baseClass) {
2114: continue;
2115: }
2116:
2117: foreach ($classes as $index => $class) {
2118: if ($typeToRemove->getClassName() === $class) {
2119: unset($classes[$index]);
2120:
2121: return TypeCombinator::union(
2122: ...array_map(static fn (string $objectClass): Type => new ObjectType($objectClass), $classes),
2123: );
2124: }
2125: }
2126: }
2127: }
2128:
2129: if ($this->isSuperTypeOf($typeToRemove)->yes()) {
2130: return $this->subtract($typeToRemove);
2131: }
2132:
2133: $classReflection = $this->getClassReflection();
2134: if ($typeToRemove instanceof UnionType && $classReflection !== null && $classReflection->getAllowedSubTypes() !== null) {
2135: // A sealed hierarchy subtracts by set difference, so the members this
2136: // type no longer holds (already subtracted) are no-ops and the rest come
2137: // off in one subtraction - the same result as removing them one at a
2138: // time, without rebuilding the subtracted union once per member.
2139: $membersToRemove = [];
2140: foreach ($typeToRemove->getTypes() as $member) {
2141: if ($member->isSuperTypeOf($this)->yes()) {
2142: return new NeverType();
2143: }
2144:
2145: $isSuperTypeOfMember = $this->isSuperTypeOf($member);
2146: if ($isSuperTypeOfMember->yes()) {
2147: $membersToRemove[] = $member;
2148: continue;
2149: }
2150: if ($isSuperTypeOfMember->maybe()) {
2151: return null;
2152: }
2153: }
2154:
2155: if ($membersToRemove === []) {
2156: return $this;
2157: }
2158:
2159: return $this->subtract(count($membersToRemove) === 1 ? $membersToRemove[0] : new UnionType($membersToRemove));
2160: }
2161:
2162: return null;
2163: }
2164:
2165: public function getFiniteTypes(): array
2166: {
2167: return $this->getEnumCases();
2168: }
2169:
2170: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
2171: {
2172: $object = new ObjectWithoutClassType();
2173: if (!$exponent instanceof NeverType && !$object->isSuperTypeOf($this)->no() && !$object->isSuperTypeOf($exponent)->no()) {
2174: return TypeCombinator::union($this, $exponent);
2175: }
2176: return new ErrorType();
2177: }
2178:
2179: public function toPhpDocNode(): TypeNode
2180: {
2181: $writtenType = $this->getAnonymousClassWrittenType();
2182: if ($writtenType !== null) {
2183: return $writtenType->toPhpDocNode();
2184: }
2185:
2186: return new FullyQualifiedNameNode($this->getClassName());
2187: }
2188:
2189: public function toNativePhpTypeNode(NativeTypePosition $position)
2190: {
2191: $writtenType = $this->getAnonymousClassWrittenType();
2192: if ($writtenType !== null) {
2193: return $writtenType->toNativePhpTypeNode($position);
2194: }
2195:
2196: $className = $this->getClassName();
2197: if ($className === '' || !$position->isClassNameAllowed()) {
2198: return null;
2199: }
2200:
2201: return new FullyQualified($className);
2202: }
2203:
2204: /**
2205: * An anonymous class cannot be named in a type, it is written as its parent class,
2206: * the intersection of the interfaces it implements, or object. Null for a named class.
2207: */
2208: private function getAnonymousClassWrittenType(): ?Type
2209: {
2210: $classReflection = $this->getClassReflection();
2211: if ($classReflection === null || !$classReflection->isAnonymous()) {
2212: return null;
2213: }
2214:
2215: $parent = $this->getParent();
2216: if ($parent !== null) {
2217: return $parent;
2218: }
2219:
2220: $interfaces = $this->getInterfaces();
2221: if (count($interfaces) === 0) {
2222: return new ObjectWithoutClassType();
2223: }
2224:
2225: return TypeCombinator::intersect(...array_values($interfaces));
2226: }
2227:
2228: public function hasTemplateOrLateResolvableType(): bool
2229: {
2230: if ($this->subtractedType === null) {
2231: return false;
2232: }
2233:
2234: return $this->subtractedType->hasTemplateOrLateResolvableType();
2235: }
2236:
2237: public function hasUnresolvedTemplateArgumentType(): bool
2238: {
2239: $subtractedType = $this->getSubtractedType();
2240:
2241: return $subtractedType !== null && $subtractedType->hasUnresolvedTemplateArgumentType();
2242: }
2243:
2244: public function toValueSet(): ValueSet
2245: {
2246: return ValueSet::createObjects($this);
2247: }
2248:
2249: }
2250: