1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\Internal\CombinationsHelper;
6: use PHPStan\Php\PhpVersion;
7: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
8: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
9: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
10: use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
11: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
12: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
13: use PHPStan\Reflection\ClassConstantReflection;
14: use PHPStan\Reflection\ClassMemberAccessAnswerer;
15: use PHPStan\Reflection\Dummy\DummyClassConstantReflection;
16: use PHPStan\Reflection\Dummy\DummyMethodReflection;
17: use PHPStan\Reflection\Dummy\DummyPropertyReflection;
18: use PHPStan\Reflection\ExtendedMethodReflection;
19: use PHPStan\Reflection\ExtendedPropertyReflection;
20: use PHPStan\Reflection\InitializerExprTypeResolver;
21: use PHPStan\Reflection\MissingConstantFromReflectionException;
22: use PHPStan\Reflection\MissingMethodFromReflectionException;
23: use PHPStan\Reflection\MissingPropertyFromReflectionException;
24: use PHPStan\Reflection\ParametersAcceptorSelector;
25: use PHPStan\Reflection\ReflectionProvider;
26: use PHPStan\Reflection\TrivialParametersAcceptor;
27: use PHPStan\Reflection\Type\IntersectionTypeUnresolvedMethodPrototypeReflection;
28: use PHPStan\Reflection\Type\IntersectionTypeUnresolvedPropertyPrototypeReflection;
29: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
30: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
31: use PHPStan\ShouldNotHappenException;
32: use PHPStan\TrinaryLogic;
33: use PHPStan\Turbo\ShadowedByTurboExtension;
34: use PHPStan\Type\Accessory\AccessoryArrayListType;
35: use PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType;
36: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
37: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
38: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
39: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
40: use PHPStan\Type\Accessory\AccessoryNumericStringType;
41: use PHPStan\Type\Accessory\AccessoryType;
42: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
43: use PHPStan\Type\Accessory\HasOffsetType;
44: use PHPStan\Type\Accessory\HasOffsetValueType;
45: use PHPStan\Type\Accessory\NonEmptyArrayType;
46: use PHPStan\Type\Constant\ConstantArrayType;
47: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
48: use PHPStan\Type\Constant\ConstantIntegerType;
49: use PHPStan\Type\Constant\ConstantStringType;
50: use PHPStan\Type\Enum\EnumCaseObjectType;
51: use PHPStan\Type\Generic\TemplateArrayType;
52: use PHPStan\Type\Generic\TemplateType;
53: use PHPStan\Type\Generic\TemplateTypeMap;
54: use PHPStan\Type\Generic\TemplateTypeVariance;
55: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
56: use PHPStan\Type\Traits\NonRemoveableTypeTrait;
57: use PHPStan\Type\Traits\OperatorTypeTrait;
58: use function array_filter;
59: use function array_intersect_key;
60: use function array_key_exists;
61: use function array_map;
62: use function array_shift;
63: use function array_unique;
64: use function array_values;
65: use function count;
66: use function get_class;
67: use function implode;
68: use function in_array;
69: use function is_int;
70: use function is_string;
71: use function ksort;
72: use function spl_object_id;
73: use function sprintf;
74: use function str_starts_with;
75: use function strcasecmp;
76: use function strlen;
77: use function substr;
78: use function usort;
79: use const PHP_INT_MAX;
80:
81: /** @api */
82: #[InstanceofDeprecated]
83: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/IntersectionType.cpp')]
84: class IntersectionType implements CompoundType
85: {
86:
87: use NonRemoveableTypeTrait;
88: use NonGeneralizableTypeTrait;
89: use OperatorTypeTrait;
90:
91: /**
92: * Sorting must not reorder $types: describe() sorts for readability, but $types is the
93: * type's value — getTypes() exposes it and callers merge array shapes in that order. It
94: * used to be sorted in place, so describing a union permanently changed what getTypes()
95: * returned, making an immutable value object's observable state depend on what had been
96: * called on it before.
97: *
98: * @var list<Type>|null
99: */
100: private ?array $sortedTypesCache = null;
101:
102: private ?TrinaryLogic $isBoolean = null;
103:
104: private ?TrinaryLogic $isFloat = null;
105:
106: private ?TrinaryLogic $isInteger = null;
107:
108: private ?TrinaryLogic $isString = null;
109:
110: private ?TrinaryLogic $isArray = null;
111:
112: private ?TrinaryLogic $isList = null;
113:
114: private ?TrinaryLogic $isConstantArray = null;
115:
116: private ?TrinaryLogic $isOversizedArray = null;
117:
118: private ?TrinaryLogic $isOffsetAccessible = null;
119:
120: private ?TrinaryLogic $isIterableAtLeastOnce = null;
121:
122: private ?TrinaryLogic $isConstantScalarValue = null;
123:
124: private ?TrinaryLogic $isCallable = null;
125:
126: /** @var array<string, Type> */
127: private array $cachedGetOffsetValueType = [];
128:
129: /** @var array<string, TrinaryLogic> */
130: private array $cachedHasOffsetValueType = [];
131:
132: /** @var array<int, string> */
133: private array $cachedDescriptions = [];
134:
135: /**
136: * @api
137: * @param list<Type> $types
138: */
139: public function __construct(private array $types)
140: {
141: if (count($types) < 2) {
142: throw new ShouldNotHappenException(sprintf(
143: 'Cannot create %s with: %s',
144: self::class,
145: implode(', ', array_map(static fn (Type $type): string => $type->describe(VerbosityLevel::value()), $types)),
146: ));
147: }
148: }
149:
150: /** @var array<int, Type> */
151: private array $generalizedTypes = [];
152:
153: /** @var array<int, IsSuperTypeOfResult> */
154: private array $superTypeOfMixedResults = [];
155:
156: public function generalize(GeneralizePrecision $precision): Type
157: {
158: // Immutable, so it generalizes the same way every time - remembered
159: // because a member shared by several nested types is otherwise
160: // generalized once per path leading to it (see ConstantArrayType::generalize()).
161: return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
162: }
163:
164: /**
165: * @return list<Type>
166: */
167: public function getTypes(): array
168: {
169: return $this->types;
170: }
171:
172: /**
173: * @return list<Type>
174: */
175: private function getSortedTypes(): array
176: {
177: return $this->sortedTypesCache ??= UnionTypeHelper::sortTypes($this->types);
178: }
179:
180: public function inferTemplateTypesOn(Type $templateType): TemplateTypeMap
181: {
182: $types = TemplateTypeMap::createEmpty();
183:
184: foreach ($this->types as $type) {
185: $types = $types->intersect($templateType->inferTemplateTypes($type));
186: }
187:
188: return $types;
189: }
190:
191: public function getReferencedClasses(): array
192: {
193: $classes = [];
194: foreach ($this->types as $type) {
195: foreach ($type->getReferencedClasses() as $className) {
196: $classes[] = $className;
197: }
198: }
199:
200: return $classes;
201: }
202:
203: public function getObjectClassNames(): array
204: {
205: $objectClassNames = [];
206: foreach ($this->types as $type) {
207: $innerObjectClassNames = $type->getObjectClassNames();
208: foreach ($innerObjectClassNames as $innerObjectClassName) {
209: $objectClassNames[] = $innerObjectClassName;
210: }
211: }
212:
213: return array_values(array_unique($objectClassNames));
214: }
215:
216: public function getObjectClassReflections(): array
217: {
218: $reflections = [];
219: foreach ($this->types as $type) {
220: foreach ($type->getObjectClassReflections() as $reflection) {
221: $reflections[] = $reflection;
222: }
223: }
224:
225: return $reflections;
226: }
227:
228: public function getArrays(): array
229: {
230: $arrays = [];
231: foreach ($this->types as $type) {
232: foreach ($type->getArrays() as $array) {
233: $arrays[] = $array;
234: }
235: }
236:
237: return $arrays;
238: }
239:
240: public function getConstantArrays(): array
241: {
242: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
243: $builder = ConstantArrayTypeBuilder::createEmpty();
244: $zero = new ConstantIntegerType(0);
245: $builder->setOffsetValueType(
246: $zero,
247: $this->getOffsetValueType($zero),
248: );
249: $one = new ConstantIntegerType(1);
250: $builder->setOffsetValueType(
251: $one,
252: $this->getOffsetValueType($one),
253: );
254: $constantArray = $builder->getArray();
255: if (!$constantArray instanceof ConstantArrayType) {
256: throw new ShouldNotHappenException();
257: }
258:
259: return [$builder->getArray()];
260: }
261:
262: $constantArrays = [];
263: foreach ($this->types as $type) {
264: foreach ($type->getConstantArrays() as $constantArray) {
265: $constantArrays[] = $constantArray;
266: }
267: }
268:
269: return $constantArrays;
270: }
271:
272: public function getConstantStrings(): array
273: {
274: $strings = [];
275: foreach ($this->types as $type) {
276: foreach ($type->getConstantStrings() as $string) {
277: $strings[] = $string;
278: }
279: }
280:
281: return $strings;
282: }
283:
284: public function accepts(Type $otherType, bool $strictTypes): AcceptsResult
285: {
286: $result = AcceptsResult::createYes();
287: foreach ($this->types as $type) {
288: $result = $result->and($type->accepts($otherType, $strictTypes));
289: }
290:
291: if (!$result->yes()) {
292: $isList = $otherType->isList();
293: $reasons = $result->reasons;
294: $verbosity = VerbosityLevel::getRecommendedLevelByType($this, $otherType);
295: if ($this->isList()->yes() && !$isList->yes()) {
296: $reasons[] = sprintf(
297: '%s %s a list.',
298: $otherType->describe($verbosity),
299: $isList->no() ? 'is not' : 'might not be',
300: );
301: }
302:
303: $isNonEmpty = $otherType->isIterableAtLeastOnce();
304: if ($this->isIterableAtLeastOnce()->yes() && !$isNonEmpty->yes()) {
305: $reasons[] = sprintf(
306: '%s %s empty.',
307: $otherType->describe($verbosity),
308: $isNonEmpty->no() ? 'is' : 'might be',
309: );
310: }
311:
312: if (count($reasons) > 0) {
313: return new AcceptsResult($result->result, $reasons);
314: }
315: }
316:
317: return $result;
318: }
319:
320: public function isSuperTypeOf(Type $otherType): IsSuperTypeOfResult
321: {
322: if ($otherType instanceof IntersectionType && $this->equals($otherType)) {
323: return IsSuperTypeOfResult::createYes();
324: }
325:
326: if ($otherType instanceof NeverType) {
327: return IsSuperTypeOfResult::createYes();
328: }
329:
330: if (get_class($otherType) === MixedType::class && $otherType->getSubtractedType() === null) {
331: // Immutable, so it compares to plain mixed the same way every time -
332: // remembered because comparing to mixed walks every nested member,
333: // and a member shared by several nested types (e.g. a snapshot of
334: // an array stored in it at every nesting level) is otherwise
335: // walked once per path leading to it.
336: return $this->superTypeOfMixedResults[(int) $otherType->isExplicitMixed()] ??= IsSuperTypeOfResult::createYes()->and(...array_map(static fn (Type $innerType) => $innerType->isSuperTypeOf($otherType), $this->types));
337: }
338:
339: return IsSuperTypeOfResult::createYes()->and(...array_map(static fn (Type $innerType) => $innerType->isSuperTypeOf($otherType), $this->types));
340: }
341:
342: public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult
343: {
344: if (($otherType instanceof self || $otherType instanceof UnionType) && !$otherType instanceof TemplateType) {
345: return $otherType->isSuperTypeOf($this);
346: }
347:
348: $result = IsSuperTypeOfResult::lazyMaxMin(
349: $this->types,
350: static fn (Type $innerType) => $otherType->isSuperTypeOf($innerType),
351: );
352:
353: if (
354: !$result->no()
355: && $this->isOversizedArray()->yes()
356: && !$otherType->isIterableAtLeastOnce()->no()
357: ) {
358: return IsSuperTypeOfResult::createYes();
359: }
360:
361: return $result;
362: }
363:
364: public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult
365: {
366: $result = AcceptsResult::lazyMaxMin(
367: $this->types,
368: static fn (Type $innerType) => $acceptingType->accepts($innerType, $strictTypes),
369: );
370:
371: // lazyMaxMin can short-circuit to Yes when array<mixed> (inside e.g. array&callable
372: // or array&hasOffsetValue) is accepted by a specific array type like array<int>,
373: // because MixedType::isAcceptedBy() always returns Yes. The isSuperTypeOf check
374: // considers the intersection holistically and catches these false positives.
375: if ($result->yes()) {
376: $isSuperType = $acceptingType->isSuperTypeOf($this);
377: if ($isSuperType->no()) {
378: return $isSuperType->toAcceptsResult();
379: }
380:
381: // A TemplateType member accepts eagerly, so lazyMaxMin's Yes may come solely from it.
382: // A Maybe from the holistic isSuperTypeOf means no member is a definite subtype, so
383: // when a TemplateType member forced the eager Yes, that Yes is untrustworthy - trust the Maybe.
384: // Only distrust when a TemplateType member itself accepts with Yes; if it accepts with Maybe,
385: // the eager Yes came from a non-template member and reflects a genuine (object-level) match.
386: if ($isSuperType->maybe()) {
387: foreach ($this->types as $innerType) {
388: if ($innerType instanceof TemplateType && $acceptingType->accepts($innerType, $strictTypes)->yes()) {
389: return $isSuperType->toAcceptsResult();
390: }
391: }
392: }
393: }
394:
395: if ($this->isOversizedArray()->yes()) {
396: if (!$result->no()) {
397: return AcceptsResult::createYes();
398: }
399: }
400:
401: return $result;
402: }
403:
404: public function equals(Type $type): bool
405: {
406: if (!$type instanceof static) {
407: return false;
408: }
409:
410: if (count($this->types) !== count($type->types)) {
411: return false;
412: }
413:
414: $otherTypes = $type->types;
415: foreach ($this->types as $innerType) {
416: $match = false;
417: foreach ($otherTypes as $i => $otherType) {
418: if (!$innerType->equals($otherType)) {
419: continue;
420: }
421:
422: $match = true;
423: unset($otherTypes[$i]);
424: break;
425: }
426:
427: if (!$match) {
428: return false;
429: }
430: }
431:
432: return count($otherTypes) === 0;
433: }
434:
435: public function describe(VerbosityLevel $level): string
436: {
437: if (isset($this->cachedDescriptions[$level->getLevelValue()])) {
438: return $this->cachedDescriptions[$level->getLevelValue()];
439: }
440:
441: return $this->cachedDescriptions[$level->getLevelValue()] = $level->handle(
442: fn (): string => $this->describeType($level),
443: fn (): string => $this->describeItself($level, true),
444: fn (): string => $this->describeItself($level, false),
445: );
446: }
447:
448: private function describeType(VerbosityLevel $level): string
449: {
450: $typeNames = [];
451: $isList = $this->isList()->yes();
452: $valueType = null;
453: foreach ($this->getSortedTypes() as $type) {
454: if ($isList) {
455: if ($type instanceof ArrayType || $type instanceof ConstantArrayType) {
456: $valueType = $type->getIterableValueType();
457: continue;
458: }
459: if ($type instanceof NonEmptyArrayType) {
460: continue;
461: }
462: }
463: if ($type instanceof AccessoryType) {
464: continue;
465: }
466: $typeNames[] = $type->generalize(GeneralizePrecision::lessSpecific())->describe($level);
467: }
468:
469: if ($isList) {
470: $isMixedValueType = MixedType::isBareMixed($valueType, $level) && !$valueType->isExplicitMixed();
471: $innerType = '';
472: if ($valueType !== null && !$isMixedValueType) {
473: $innerType = sprintf('<%s>', $valueType->describe($level));
474: }
475:
476: $typeNames[] = 'list' . $innerType;
477: }
478:
479: usort($typeNames, static function ($a, $b) {
480: $cmp = strcasecmp($a, $b);
481: if ($cmp !== 0) {
482: return $cmp;
483: }
484:
485: return $a <=> $b;
486: });
487:
488: return implode('&', $typeNames);
489: }
490:
491: private function describeItself(VerbosityLevel $level, bool $skipAccessoryTypes): string
492: {
493: $baseTypes = [];
494: $typesToDescribe = [];
495: $skipTypeNames = [];
496:
497: $nonEmptyStr = false;
498: $nonFalsyStr = false;
499: $isList = $this->isList()->yes();
500: $isArray = $this->isArray()->yes();
501: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
502: // When a TemplateArrayType, a RecursiveType or a reference to one carries the array refinement,
503: // we describe it via its own describe() (e.g. "T of array") rather than
504: // collapsing it into a generic `array<...>` prefix. In that case the
505: // `NonEmptyArrayType` and `AccessoryArrayListType` markers must
506: // describe themselves explicitly — they cannot be absorbed into a
507: // non-existent `non-empty-array` prefix.
508: $hasTemplateArray = false;
509: if ($isArray || $isList) {
510: foreach ($this->types as $type) {
511: if ($type instanceof TemplateArrayType || $type instanceof RecursiveType || $type instanceof RecursiveTypeReference) {
512: $hasTemplateArray = true;
513: break;
514: }
515: }
516: }
517: $describedTypes = [];
518: foreach ($this->getSortedTypes() as $i => $type) {
519: if ($type instanceof AccessoryNonEmptyStringType
520: || $type instanceof AccessoryLiteralStringType
521: || $type instanceof AccessoryNumericStringType
522: || $type instanceof AccessoryNonFalsyStringType
523: || $type instanceof AccessoryLowercaseStringType
524: || $type instanceof AccessoryUppercaseStringType
525: || $type instanceof AccessoryDecimalIntegerStringType
526: ) {
527: if (
528: ($type instanceof AccessoryLowercaseStringType || $type instanceof AccessoryUppercaseStringType)
529: && !$level->isPrecise()
530: && !$level->isCache()
531: ) {
532: continue;
533: }
534: if ($type instanceof AccessoryNonFalsyStringType) {
535: $nonFalsyStr = true;
536: }
537: if ($type instanceof AccessoryNonEmptyStringType) {
538: $nonEmptyStr = true;
539: }
540: if ($nonEmptyStr && $nonFalsyStr) {
541: // prevent redundant 'non-empty-string&non-falsy-string'
542: foreach ($typesToDescribe as $key => $typeToDescribe) {
543: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
544: continue;
545: }
546:
547: unset($typesToDescribe[$key]);
548: }
549: }
550:
551: $typesToDescribe[$i] = $type;
552: $skipTypeNames[] = 'string';
553: continue;
554: }
555: if ($isList || $isArray) {
556: if ($type instanceof TemplateArrayType) {
557: // Preserve the template's own describe (e.g. "T of array")
558: // instead of collapsing it to a generic array shape — the
559: // other intersection members already carry the array
560: // refinement.
561: $describedTypes[$i] = $type->describe($level);
562: continue;
563: }
564: if ($type instanceof ArrayType && !$isList && $type->getKeyTemplate() !== null) {
565: // array<K of 'a'|'b', V> keeps declaring its template
566: $description = $type->describe($level);
567: $describedTypes[$i] = $isNonEmptyArray && str_starts_with($description, 'array<') ? 'non-empty-' . $description : $description;
568: continue;
569: }
570: if ($type instanceof ArrayType) {
571: $keyType = $type->getKeyType();
572: $valueType = $type->getItemType();
573: if ($isList) {
574: $isMixedValueType = MixedType::isBareMixed($valueType, $level) && !$valueType->isExplicitMixed();
575: $valueTypeDescription = '';
576: if (
577: $level->isCache()
578: && !($keyType instanceof IntegerRangeType && $keyType->getMin() === 0 && $keyType->getMax() === null)
579: ) {
580: // the cache key of list<X> with fewer keys than int<0, max>, as array<0|1, X>&list
581: $valueTypeDescription = sprintf('<%s, %s>', $keyType->describe($level), $valueType->describe($level));
582: } elseif (!$isMixedValueType) {
583: $valueTypeDescription = sprintf('<%s>', $valueType->describe($level));
584: }
585:
586: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-list' : 'list') . $valueTypeDescription;
587: } else {
588: $isMixedKeyType = MixedType::isBareMixed($keyType, $level) && !$keyType->isExplicitMixed();
589: $isMixedValueType = MixedType::isBareMixed($valueType, $level) && !$valueType->isExplicitMixed();
590: $typeDescription = '';
591: if (!$isMixedKeyType) {
592: $typeDescription = sprintf('<%s, %s>', $keyType->describe($level), $valueType->describe($level));
593: } elseif (!$isMixedValueType) {
594: $typeDescription = sprintf('<%s>', $valueType->describe($level));
595: }
596:
597: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-array' : 'array') . $typeDescription;
598: }
599: continue;
600: } elseif ($type instanceof ConstantArrayType) {
601: $description = $type->describe($level);
602: $kind = str_starts_with($description, 'list') ? 'list' : 'array';
603: $descriptionWithoutKind = substr($description, strlen($kind));
604: $begin = $isList ? 'list' : 'array';
605: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
606: $begin = 'non-empty-' . $begin;
607: }
608:
609: $describedTypes[$i] = $begin . $descriptionWithoutKind;
610: continue;
611: }
612: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
613: if ($hasTemplateArray) {
614: $describedTypes[$i] = $type->describe($level);
615: }
616: continue;
617: }
618: }
619:
620: if ($type instanceof CallableType && $type->isCommonCallable()) {
621: $typesToDescribe[$i] = $type;
622: $skipTypeNames[] = 'object';
623: $skipTypeNames[] = 'string';
624: continue;
625: }
626:
627: if (!$type instanceof AccessoryType) {
628: $baseTypes[$i] = $type;
629: continue;
630: }
631:
632: if ($skipAccessoryTypes) {
633: continue;
634: }
635:
636: $typesToDescribe[$i] = $type;
637: }
638:
639: foreach ($baseTypes as $i => $type) {
640: $typeDescription = $type->describe($level);
641:
642: if (in_array($typeDescription, ['object', 'string'], true) && in_array($typeDescription, $skipTypeNames, true)) {
643: foreach ($typesToDescribe as $j => $typeToDescribe) {
644: if ($typeToDescribe instanceof CallableType && $typeToDescribe->isCommonCallable()) {
645: $describedTypes[$i] = 'callable-' . $typeDescription;
646: unset($typesToDescribe[$j]);
647: continue 2;
648: }
649: }
650: }
651:
652: if (in_array($typeDescription, $skipTypeNames, true)) {
653: continue;
654: }
655:
656: $describedTypes[$i] = $type->describe($level);
657: }
658:
659: foreach ($typesToDescribe as $i => $typeToDescribe) {
660: $describedTypes[$i] = $typeToDescribe->describe($level);
661: }
662:
663: ksort($describedTypes);
664:
665: return implode('&', $describedTypes);
666: }
667:
668: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
669: {
670: return $this->intersectTypes(static fn (Type $type): Type => $type->getTemplateType($ancestorClassName, $templateTypeName));
671: }
672:
673: public function isObject(): TrinaryLogic
674: {
675: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isObject());
676: }
677:
678: public function getClassStringType(): Type
679: {
680: return $this->intersectTypes(static fn (Type $type): Type => $type->getClassStringType());
681: }
682:
683: public function isEnum(): TrinaryLogic
684: {
685: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isEnum());
686: }
687:
688: public function canAccessProperties(): TrinaryLogic
689: {
690: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessProperties());
691: }
692:
693: public function hasProperty(string $propertyName): TrinaryLogic
694: {
695: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasProperty($propertyName));
696: }
697:
698: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
699: {
700: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
701: }
702:
703: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
704: {
705: $propertyPrototypes = [];
706: foreach ($this->types as $type) {
707: if (!$type->hasProperty($propertyName)->yes()) {
708: continue;
709: }
710:
711: $propertyPrototypes[] = $type->getUnresolvedPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
712: }
713:
714: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
715: }
716:
717: public function hasInstanceProperty(string $propertyName): TrinaryLogic
718: {
719: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasInstanceProperty($propertyName));
720: }
721:
722: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
723: {
724: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
725: }
726:
727: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
728: {
729: $propertyPrototypes = [];
730: foreach ($this->types as $type) {
731: if (!$type->hasInstanceProperty($propertyName)->yes()) {
732: continue;
733: }
734:
735: $propertyPrototypes[] = $type->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->withFechedOnType($this);
736: }
737:
738: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
739: }
740:
741: public function hasStaticProperty(string $propertyName): TrinaryLogic
742: {
743: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasStaticProperty($propertyName));
744: }
745:
746: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
747: {
748: return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty();
749: }
750:
751: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
752: {
753: $propertyPrototypes = [];
754: foreach ($this->types as $type) {
755: if (!$type->hasStaticProperty($propertyName)->yes()) {
756: continue;
757: }
758:
759: $propertyPrototypes[] = $type->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
760: }
761:
762: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
763: }
764:
765: /**
766: * @param list<UnresolvedPropertyPrototypeReflection> $propertyPrototypes
767: */
768: private function createUnresolvedPropertyPrototype(string $propertyName, array $propertyPrototypes): UnresolvedPropertyPrototypeReflection
769: {
770: // a member like T of mixed has every property only as a placeholder,
771: // it must not override the property declared by another member
772: $declaredPropertyPrototypes = array_values(array_filter(
773: $propertyPrototypes,
774: static fn (UnresolvedPropertyPrototypeReflection $prototype): bool => !$prototype->getNakedProperty() instanceof DummyPropertyReflection,
775: ));
776: if (count($declaredPropertyPrototypes) > 0) {
777: $propertyPrototypes = $declaredPropertyPrototypes;
778: }
779:
780: $propertiesCount = count($propertyPrototypes);
781: if ($propertiesCount === 0) {
782: throw new MissingPropertyFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $propertyName);
783: }
784:
785: if ($propertiesCount === 1) {
786: return $propertyPrototypes[0];
787: }
788:
789: return new IntersectionTypeUnresolvedPropertyPrototypeReflection($propertyPrototypes);
790: }
791:
792: public function canCallMethods(): TrinaryLogic
793: {
794: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canCallMethods());
795: }
796:
797: public function hasMethod(string $methodName): TrinaryLogic
798: {
799: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasMethod($methodName));
800: }
801:
802: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
803: {
804: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
805: }
806:
807: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
808: {
809: $methodPrototypes = [];
810: foreach ($this->types as $type) {
811: if (!$type->hasMethod($methodName)->yes()) {
812: continue;
813: }
814:
815: $methodPrototypes[] = $type->getUnresolvedMethodPrototype($methodName, $scope)->withCalledOnType($this);
816: }
817:
818: // a member like T of mixed has every method only as a placeholder,
819: // it must not override the method declared by another member
820: $declaredMethodPrototypes = array_values(array_filter(
821: $methodPrototypes,
822: static fn (UnresolvedMethodPrototypeReflection $prototype): bool => !$prototype->getNakedMethod() instanceof DummyMethodReflection,
823: ));
824: if (count($declaredMethodPrototypes) > 0) {
825: $methodPrototypes = $declaredMethodPrototypes;
826: }
827:
828: $methodsCount = count($methodPrototypes);
829: if ($methodsCount === 0) {
830: throw new MissingMethodFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $methodName);
831: }
832:
833: if ($methodsCount === 1) {
834: return $methodPrototypes[0];
835: }
836:
837: return new IntersectionTypeUnresolvedMethodPrototypeReflection($methodName, $methodPrototypes);
838: }
839:
840: public function canAccessConstants(): TrinaryLogic
841: {
842: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessConstants());
843: }
844:
845: public function hasConstant(string $constantName): TrinaryLogic
846: {
847: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasConstant($constantName));
848: }
849:
850: public function getConstant(string $constantName): ClassConstantReflection
851: {
852: $dummyConstant = null;
853: foreach ($this->types as $type) {
854: if (!$type->hasConstant($constantName)->yes()) {
855: continue;
856: }
857:
858: $constant = $type->getConstant($constantName);
859:
860: // a member like T of mixed has every constant only as a placeholder,
861: // it must not override the constant declared by another member
862: if ($constant instanceof DummyClassConstantReflection) {
863: $dummyConstant ??= $constant;
864: continue;
865: }
866:
867: return $constant;
868: }
869:
870: if ($dummyConstant !== null) {
871: return $dummyConstant;
872: }
873:
874: throw new MissingConstantFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $constantName);
875: }
876:
877: public function isIterable(): TrinaryLogic
878: {
879: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isIterable());
880: }
881:
882: public function isIterableAtLeastOnce(): TrinaryLogic
883: {
884: return $this->isIterableAtLeastOnce ??= $this->isCallable()->yes() && $this->isArray()->yes()
885: ? TrinaryLogic::createYes()
886: : $this->intersectResults(
887: static fn (Type $type): TrinaryLogic => $type->isIterableAtLeastOnce(),
888: static fn (Type $type): bool => !$type->isIterable()->no(),
889: );
890: }
891:
892: public function getArraySize(): Type
893: {
894: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
895: return new ConstantIntegerType(2);
896: }
897:
898: $arraySize = $this->intersectTypes(static fn (Type $type): Type => $type->getArraySize());
899:
900: $knownOffsets = [];
901: foreach ($this->types as $type) {
902: if (!($type instanceof HasOffsetValueType) && !($type instanceof HasOffsetType)) {
903: continue;
904: }
905:
906: $knownOffsets[$type->getOffsetType()->getValue()] = true;
907: }
908:
909: if ($this->isList()->yes() && $this->isIterableAtLeastOnce()->yes()) {
910: $knownOffsets[0] = true;
911: }
912:
913: if ($knownOffsets !== []) {
914: return TypeCombinator::intersect($arraySize, IntegerRangeType::fromInterval(count($knownOffsets), null));
915: }
916:
917: return $arraySize;
918: }
919:
920: public function getIterableKeyType(): Type
921: {
922: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
923: return new UnionType([new ConstantIntegerType(0), new ConstantIntegerType(1)]);
924: }
925: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType());
926: }
927:
928: public function getFirstIterableKeyType(): Type
929: {
930: return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableKeyType());
931: }
932:
933: public function getLastIterableKeyType(): Type
934: {
935: return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableKeyType());
936: }
937:
938: public function getIterableValueType(): Type
939: {
940: $result = $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType());
941: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
942: return TypeCombinator::intersect(
943: $result,
944: new UnionType([
945: new ObjectWithoutClassType(),
946: new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]),
947: ]),
948: );
949: }
950: return $result;
951: }
952:
953: public function getFirstIterableValueType(): Type
954: {
955: return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableValueType());
956: }
957:
958: public function getLastIterableValueType(): Type
959: {
960: return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableValueType());
961: }
962:
963: public function isArray(): TrinaryLogic
964: {
965: return $this->isArray ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isArray());
966: }
967:
968: public function isConstantArray(): TrinaryLogic
969: {
970: return $this->isConstantArray ??= $this->isCallable()->yes() && $this->isArray()->yes()
971: ? TrinaryLogic::createYes()
972: : $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantArray());
973: }
974:
975: public function isOversizedArray(): TrinaryLogic
976: {
977: return $this->isOversizedArray ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOversizedArray());
978: }
979:
980: public function isList(): TrinaryLogic
981: {
982: return $this->isList ??= $this->isCallable()->yes() && $this->isArray()->yes()
983: ? TrinaryLogic::createYes()
984: : $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isList());
985: }
986:
987: public function isString(): TrinaryLogic
988: {
989: return $this->isString ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isString());
990: }
991:
992: public function isNumericString(): TrinaryLogic
993: {
994: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNumericString());
995: }
996:
997: public function isDecimalIntegerString(): TrinaryLogic
998: {
999: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isDecimalIntegerString());
1000: }
1001:
1002: public function isNonEmptyString(): TrinaryLogic
1003: {
1004: if ($this->isCallable()->yes() && $this->isString()->yes()) {
1005: return TrinaryLogic::createYes();
1006: }
1007: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonEmptyString());
1008: }
1009:
1010: public function isNonFalsyString(): TrinaryLogic
1011: {
1012: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonFalsyString());
1013: }
1014:
1015: public function isLiteralString(): TrinaryLogic
1016: {
1017: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLiteralString());
1018: }
1019:
1020: public function getStringRefinement(): ?int
1021: {
1022: $cells = StringRefinement::ALL;
1023: foreach ($this->types as $type) {
1024: $typeCells = $type->getStringRefinement();
1025: if ($typeCells === null) {
1026: return null;
1027: }
1028: $cells &= $typeCells;
1029: }
1030:
1031: return $cells;
1032: }
1033:
1034: public function isLowercaseString(): TrinaryLogic
1035: {
1036: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLowercaseString());
1037: }
1038:
1039: public function isUppercaseString(): TrinaryLogic
1040: {
1041: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isUppercaseString());
1042: }
1043:
1044: public function isClassString(): TrinaryLogic
1045: {
1046: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isClassString());
1047: }
1048:
1049: public function getClassStringObjectType(): Type
1050: {
1051: return $this->intersectTypes(static fn (Type $type): Type => $type->getClassStringObjectType());
1052: }
1053:
1054: public function getObjectTypeOrClassStringObjectType(): Type
1055: {
1056: return $this->intersectTypes(static fn (Type $type): Type => $type->getObjectTypeOrClassStringObjectType());
1057: }
1058:
1059: public function isVoid(): TrinaryLogic
1060: {
1061: return TrinaryLogic::createNo();
1062: }
1063:
1064: public function isScalar(): TrinaryLogic
1065: {
1066: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isScalar());
1067: }
1068:
1069: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1070: {
1071: return $this->intersectResults(
1072: static fn (Type $innerType): TrinaryLogic => $innerType->looseCompare($type, $phpVersion)->toTrinaryLogic(),
1073: )->toBooleanType();
1074: }
1075:
1076: public function isOffsetAccessible(): TrinaryLogic
1077: {
1078: return $this->isOffsetAccessible ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessible());
1079: }
1080:
1081: public function isOffsetAccessLegal(): TrinaryLogic
1082: {
1083: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessLegal());
1084: }
1085:
1086: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1087: {
1088: $cacheKey = $offsetType->describe(VerbosityLevel::cache());
1089: if (isset($this->cachedHasOffsetValueType[$cacheKey])) {
1090: return $this->cachedHasOffsetValueType[$cacheKey];
1091: }
1092: return $this->cachedHasOffsetValueType[$cacheKey] = $this->doHasOffsetValueType($offsetType);
1093: }
1094:
1095: private function doHasOffsetValueType(Type $offsetType): TrinaryLogic
1096: {
1097: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
1098: $arrayKeyOffsetType = $offsetType->toArrayKey();
1099: $callableArrayOffsetType = new UnionType([new ConstantIntegerType(0), new ConstantIntegerType(1)]);
1100:
1101: return $callableArrayOffsetType->isSuperTypeOf($arrayKeyOffsetType)->result;
1102: }
1103:
1104: if ($this->isList()->yes()) {
1105: $arrayKeyOffsetType = $offsetType->toArrayKey();
1106:
1107: $negative = IntegerRangeType::fromInterval(null, -1);
1108: if ($negative->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1109: return TrinaryLogic::createNo();
1110: }
1111:
1112: $size = $this->getArraySize();
1113: if ($size instanceof IntegerRangeType && $size->getMin() !== null) {
1114: $knownOffsets = IntegerRangeType::fromInterval(0, $size->getMin() - 1);
1115: } elseif ($size instanceof ConstantIntegerType) {
1116: $knownOffsets = IntegerRangeType::fromInterval(0, $size->getValue() - 1);
1117: } elseif ($this->isIterableAtLeastOnce()->yes()) {
1118: $knownOffsets = new ConstantIntegerType(0);
1119: } else {
1120: $knownOffsets = null;
1121: }
1122:
1123: if ($knownOffsets !== null && $knownOffsets->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1124: return TrinaryLogic::createYes();
1125: }
1126:
1127: foreach ($this->types as $type) {
1128: if (!$type instanceof HasOffsetValueType && !$type instanceof HasOffsetType) {
1129: continue;
1130: }
1131:
1132: foreach ($type->getOffsetType()->getConstantScalarValues() as $constantScalarValue) {
1133: if (!is_int($constantScalarValue)) {
1134: continue;
1135: }
1136: if (IntegerRangeType::fromInterval(0, $constantScalarValue)->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1137: return TrinaryLogic::createYes();
1138: }
1139: }
1140: }
1141: }
1142:
1143: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasOffsetValueType($offsetType));
1144: }
1145:
1146: public function getOffsetValueType(Type $offsetType): Type
1147: {
1148: $cacheKey = $offsetType->describe(VerbosityLevel::cache());
1149: if (isset($this->cachedGetOffsetValueType[$cacheKey])) {
1150: return $this->cachedGetOffsetValueType[$cacheKey];
1151: }
1152: return $this->cachedGetOffsetValueType[$cacheKey] = $this->doGetOffsetValueType($offsetType);
1153: }
1154:
1155: private function doGetOffsetValueType(Type $offsetType): Type
1156: {
1157: $result = $this->intersectTypes(static fn (Type $type): Type => $type->getOffsetValueType($offsetType));
1158: if ($this->isOversizedArray()->yes()) {
1159: return TypeUtils::toBenevolentUnion($result);
1160: }
1161:
1162: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
1163: $arrayKeyOffsetType = $offsetType->toArrayKey();
1164: if ((new ConstantIntegerType(0))->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1165: $narrowedType = new UnionType([new ClassStringType(), new ObjectWithoutClassType()]);
1166: } elseif ((new ConstantIntegerType(1))->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1167: $narrowedType = new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]);
1168: } else {
1169: $narrowedType = new UnionType([new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]), new ObjectWithoutClassType()]);
1170: }
1171: $result = TypeCombinator::intersect($result, $narrowedType);
1172: }
1173:
1174: return $result;
1175: }
1176:
1177: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1178: {
1179: if ($this->isOversizedArray()->yes()) {
1180: return $this->intersectTypes(static function (Type $type) use ($offsetType, $valueType): Type {
1181: // avoid new HasOffsetValueType being intersected with oversized array
1182: if (!$type instanceof ArrayType) {
1183: return $type->setOffsetValueType($offsetType, $valueType);
1184: }
1185:
1186: if (!$offsetType instanceof ConstantStringType && !$offsetType instanceof ConstantIntegerType) {
1187: return $type->setOffsetValueType($offsetType, $valueType);
1188: }
1189:
1190: if (!$offsetType->isSuperTypeOf($type->getKeyType())->yes()) {
1191: return $type->setOffsetValueType($offsetType, $valueType);
1192: }
1193:
1194: return new IntersectionType([
1195: new ArrayType(
1196: TypeCombinator::union($type->getKeyType(), $offsetType),
1197: TypeCombinator::union($type->getItemType(), $valueType),
1198: ),
1199: new NonEmptyArrayType(),
1200: ]);
1201: });
1202: }
1203:
1204: $result = $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType));
1205:
1206: if (
1207: $offsetType !== null
1208: && $this->isList()->yes()
1209: && !$result->isList()->yes()
1210: ) {
1211: if ($this->isIterableAtLeastOnce()->yes() && (new ConstantIntegerType(1))->isSuperTypeOf($offsetType)->yes()) {
1212: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1213: } else {
1214: foreach ($this->types as $type) {
1215: if (!$type instanceof HasOffsetValueType && !$type instanceof HasOffsetType) {
1216: continue;
1217: }
1218:
1219: foreach ($type->getOffsetType()->getConstantScalarValues() as $constantScalarValue) {
1220: if (!is_int($constantScalarValue)) {
1221: continue;
1222: }
1223: // no offset exists past PHP_INT_MAX: the list may grow up to it
1224: $maxListOffset = $constantScalarValue < PHP_INT_MAX ? $constantScalarValue + 1 : null;
1225: if (IntegerRangeType::fromInterval(0, $maxListOffset)->isSuperTypeOf($offsetType)->yes()) {
1226: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1227: break 2;
1228: }
1229: }
1230: }
1231: }
1232: }
1233:
1234: if (
1235: $this->isList()->yes()
1236: && $offsetType !== null
1237: && $offsetType->toArrayKey()->isInteger()->yes()
1238: && $this->getIterableValueType()->isArray()->yes()
1239: ) {
1240: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1241: }
1242:
1243: return $result;
1244: }
1245:
1246: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1247: {
1248: return $this->intersectTypes(static fn (Type $type): Type => $type->setExistingOffsetValueType($offsetType, $valueType));
1249: }
1250:
1251: public function unsetOffset(Type $offsetType): Type
1252: {
1253: return $this->intersectTypes(static fn (Type $type): Type => $type->unsetOffset($offsetType));
1254: }
1255:
1256: public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
1257: {
1258: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArrayFiltered($filterValueType, $strict));
1259: }
1260:
1261: public function getKeysArray(): Type
1262: {
1263: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArray());
1264: }
1265:
1266: public function getValuesArray(): Type
1267: {
1268: $cb = static fn (Type $type): Type => $type->getValuesArray();
1269: if ($this->isList()->yes()) {
1270: return $this;
1271: }
1272: return $this->intersectTypes($cb);
1273: }
1274:
1275: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
1276: {
1277: return $this->intersectTypes(static fn (Type $type): Type => $type->chunkArray($lengthType, $preserveKeys));
1278: }
1279:
1280: public function fillKeysArray(Type $valueType): Type
1281: {
1282: return $this->intersectTypes(static fn (Type $type): Type => $type->fillKeysArray($valueType));
1283: }
1284:
1285: public function flipArray(): Type
1286: {
1287: return $this->intersectTypes(static fn (Type $type): Type => $type->flipArray());
1288: }
1289:
1290: public function intersectKeyArray(Type $otherArraysType): Type
1291: {
1292: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->intersectKeyArray($otherArraysType));
1293: }
1294:
1295: public function popArray(): Type
1296: {
1297: if ($this->isList()->yes()) {
1298: // hasOffsetValue(n, T) on a list proves indices 0..n exist; popping
1299: // removes the highest index, so offsets up to n - 1 survive. Their
1300: // values are unknown - the value known at n may have been the popped one.
1301: $members = [];
1302: foreach ($this->types as $type) {
1303: if ($type instanceof TemplateType) {
1304: $members[] = $type;
1305: continue;
1306: }
1307: if ($type instanceof HasOffsetValueType || $type instanceof HasOffsetType) {
1308: $offsetType = $type->getOffsetType();
1309: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1310: $members[] = new HasOffsetType(new ConstantIntegerType($offsetType->getValue() - 1));
1311: }
1312: continue;
1313: }
1314: $members[] = $type->popArray();
1315: }
1316:
1317: return TypeCombinator::intersect(...$members);
1318: }
1319:
1320: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->popArray());
1321: }
1322:
1323: public function reverseArray(TrinaryLogic $preserveKeys): Type
1324: {
1325: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->reverseArray($preserveKeys));
1326: }
1327:
1328: public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Type
1329: {
1330: return $this->intersectTypes(static fn (Type $type): Type => $type->searchArray($needleType, $strict));
1331: }
1332:
1333: public function shiftArray(): Type
1334: {
1335: if ($this->isList()->yes()) {
1336: // shifting a list reindexes: index n's value always moves to n - 1
1337: $members = [];
1338: foreach ($this->types as $type) {
1339: if ($type instanceof TemplateType) {
1340: $members[] = $type;
1341: continue;
1342: }
1343: if ($type instanceof HasOffsetValueType) {
1344: $offsetType = $type->getOffsetType();
1345: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1346: $members[] = new HasOffsetValueType(new ConstantIntegerType($offsetType->getValue() - 1), $type->getValueType());
1347: }
1348: continue;
1349: }
1350: if ($type instanceof HasOffsetType) {
1351: $offsetType = $type->getOffsetType();
1352: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1353: $members[] = new HasOffsetType(new ConstantIntegerType($offsetType->getValue() - 1));
1354: }
1355: continue;
1356: }
1357: $members[] = $type->shiftArray();
1358: }
1359:
1360: return TypeCombinator::intersect(...$members);
1361: }
1362:
1363: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->shiftArray());
1364: }
1365:
1366: public function shuffleArray(): Type
1367: {
1368: $cb = static fn (Type $type): Type => $type->shuffleArray();
1369: if ($this->isList()->yes()) {
1370: return $this->intersectTypesPreserveTemplateType($cb);
1371: }
1372: return $this->intersectTypes($cb);
1373: }
1374:
1375: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
1376: {
1377: $result = $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->sliceArray($offsetType, $lengthType, $preserveKeys));
1378:
1379: if (
1380: $this->isList()->yes()
1381: && $this->isIterableAtLeastOnce()->yes()
1382: && (new ConstantIntegerType(0))->isSuperTypeOf($offsetType)->yes()
1383: && IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($lengthType)->yes()
1384: ) {
1385: $result = TypeCombinator::intersect($result, new NonEmptyArrayType());
1386: }
1387:
1388: return $result;
1389: }
1390:
1391: public function spliceArray(Type $offsetType, Type $lengthType, Type $replacementType): Type
1392: {
1393: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->spliceArray($offsetType, $lengthType, $replacementType));
1394: }
1395:
1396: public function truncateListToSize(Type $sizeType): Type
1397: {
1398: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->truncateListToSize($sizeType));
1399: }
1400:
1401: public function makeListMaybe(): Type
1402: {
1403: return $this->intersectTypes(static fn (Type $type): Type => $type->makeListMaybe());
1404: }
1405:
1406: public function mapValueType(callable $cb): Type
1407: {
1408: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->mapValueType($cb));
1409: }
1410:
1411: public function mapKeyType(callable $cb): Type
1412: {
1413: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->mapKeyType($cb));
1414: }
1415:
1416: public function makeAllArrayKeysOptional(): Type
1417: {
1418: return $this->intersectTypes(static fn (Type $type): Type => $type->makeAllArrayKeysOptional());
1419: }
1420:
1421: public function changeKeyCaseArray(?int $case): Type
1422: {
1423: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->changeKeyCaseArray($case));
1424: }
1425:
1426: public function filterArrayRemovingFalsey(): Type
1427: {
1428: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->filterArrayRemovingFalsey());
1429: }
1430:
1431: public function getEnumCases(): array
1432: {
1433: $compare = [];
1434: foreach ($this->types as $type) {
1435: $oneType = [];
1436: foreach ($type->getEnumCases() as $enumCase) {
1437: $oneType[$enumCase->getClassName() . '::' . $enumCase->getEnumCaseName()] = $enumCase;
1438: }
1439: $compare[] = $oneType;
1440: }
1441:
1442: return array_values(array_intersect_key(...$compare));
1443: }
1444:
1445: public function getEnumCaseObject(): ?EnumCaseObjectType
1446: {
1447: $singleCase = null;
1448: foreach ($this->types as $type) {
1449: $caseObject = $type->getEnumCaseObject();
1450: if ($caseObject === null) {
1451: continue;
1452: }
1453:
1454: if ($singleCase !== null) {
1455: return null;
1456: }
1457:
1458: $singleCase = $caseObject;
1459: }
1460:
1461: return $singleCase;
1462: }
1463:
1464: public function isCallable(): TrinaryLogic
1465: {
1466: return $this->isCallable ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCallable());
1467: }
1468:
1469: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1470: {
1471: $yesAcceptors = [];
1472:
1473: foreach ($this->types as $type) {
1474: if (!$type->isCallable()->yes()) {
1475: continue;
1476: }
1477: $yesAcceptors[] = $type->getCallableParametersAcceptors($scope);
1478: }
1479:
1480: if (count($yesAcceptors) === 0) {
1481: if ($this->isCallable()->no()) {
1482: throw new ShouldNotHappenException();
1483: }
1484:
1485: return [new TrivialParametersAcceptor()];
1486: }
1487:
1488: $result = [];
1489: $combinations = CombinationsHelper::combinations($yesAcceptors);
1490: foreach ($combinations as $combination) {
1491: $combined = ParametersAcceptorSelector::combineAcceptors($combination);
1492: if (!$combined instanceof CallableParametersAcceptor) {
1493: throw new ShouldNotHappenException();
1494: }
1495: $result[] = $combined;
1496: }
1497:
1498: return $result;
1499: }
1500:
1501: public function isCloneable(): TrinaryLogic
1502: {
1503: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCloneable());
1504: }
1505:
1506: public function isSmallerThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1507: {
1508: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThan($otherType, $phpVersion));
1509: }
1510:
1511: public function isSmallerThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1512: {
1513: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThanOrEqual($otherType, $phpVersion));
1514: }
1515:
1516: public function getKindMask(): int
1517: {
1518: $mask = TypeKind::ALL;
1519: foreach ($this->types as $type) {
1520: $mask &= $type->getKindMask();
1521: }
1522:
1523: return $mask;
1524: }
1525:
1526: public function isNull(): TrinaryLogic
1527: {
1528: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNull());
1529: }
1530:
1531: public function isConstantValue(): TrinaryLogic
1532: {
1533: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantValue());
1534: }
1535:
1536: public function isConstantScalarValue(): TrinaryLogic
1537: {
1538: return $this->isConstantScalarValue ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantScalarValue());
1539: }
1540:
1541: public function getConstantScalarTypes(): array
1542: {
1543: $scalarTypes = [];
1544: foreach ($this->types as $type) {
1545: foreach ($type->getConstantScalarTypes() as $scalarType) {
1546: $scalarTypes[] = $scalarType;
1547: }
1548: }
1549:
1550: return $scalarTypes;
1551: }
1552:
1553: public function getConstantScalarValues(): array
1554: {
1555: $values = [];
1556: foreach ($this->types as $type) {
1557: foreach ($type->getConstantScalarValues() as $value) {
1558: $values[] = $value;
1559: }
1560: }
1561:
1562: return $values;
1563: }
1564:
1565: public function isTrue(): TrinaryLogic
1566: {
1567: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isTrue());
1568: }
1569:
1570: public function isFalse(): TrinaryLogic
1571: {
1572: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFalse());
1573: }
1574:
1575: public function isBoolean(): TrinaryLogic
1576: {
1577: return $this->isBoolean ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isBoolean());
1578: }
1579:
1580: public function isFloat(): TrinaryLogic
1581: {
1582: return $this->isFloat ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFloat());
1583: }
1584:
1585: public function isInteger(): TrinaryLogic
1586: {
1587: return $this->isInteger ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isInteger());
1588: }
1589:
1590: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1591: {
1592: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThan($type, $phpVersion));
1593: }
1594:
1595: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1596: {
1597: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThanOrEqual($type, $phpVersion));
1598: }
1599:
1600: public function getSmallerType(PhpVersion $phpVersion): Type
1601: {
1602: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerType($phpVersion));
1603: }
1604:
1605: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
1606: {
1607: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerOrEqualType($phpVersion));
1608: }
1609:
1610: public function getGreaterType(PhpVersion $phpVersion): Type
1611: {
1612: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterType($phpVersion));
1613: }
1614:
1615: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
1616: {
1617: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterOrEqualType($phpVersion));
1618: }
1619:
1620: public function toBoolean(): BooleanType
1621: {
1622: $type = $this->intersectTypes(static fn (Type $type): BooleanType => $type->toBoolean());
1623:
1624: if (!$type instanceof BooleanType) {
1625: return new BooleanType();
1626: }
1627:
1628: return $type;
1629: }
1630:
1631: public function toNumber(): Type
1632: {
1633: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toNumber());
1634:
1635: return $type;
1636: }
1637:
1638: public function toBitwiseNotType(): Type
1639: {
1640: return $this->intersectTypes(static fn (Type $type): Type => $type->toBitwiseNotType());
1641: }
1642:
1643: public function toGetClassResultType(): Type
1644: {
1645: return $this->intersectTypes(static fn (Type $type): Type => $type->toGetClassResultType());
1646: }
1647:
1648: public function toClassConstantType(ReflectionProvider $reflectionProvider): Type
1649: {
1650: return $this->intersectTypes(static fn (Type $type): Type => $type->toClassConstantType($reflectionProvider));
1651: }
1652:
1653: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
1654: {
1655: $types = [];
1656: $uncertainty = false;
1657: foreach ($this->getTypes() as $innerType) {
1658: $result = $innerType->toObjectTypeForInstanceofCheck();
1659: $types[] = $result->type;
1660: if (!$result->uncertainty) {
1661: continue;
1662: }
1663:
1664: $uncertainty = true;
1665: }
1666:
1667: return new ClassNameToObjectTypeResult(TypeCombinator::intersect(...$types), $uncertainty);
1668: }
1669:
1670: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
1671: {
1672: $types = [];
1673: $uncertainty = false;
1674: foreach ($this->getTypes() as $innerType) {
1675: $result = $innerType->toObjectTypeForIsACheck($objectOrClassType, $allowString, $allowSameClass);
1676: $types[] = $result->type;
1677: if (!$result->uncertainty) {
1678: continue;
1679: }
1680:
1681: $uncertainty = true;
1682: }
1683:
1684: return new ClassNameToObjectTypeResult(TypeCombinator::intersect(...$types), $uncertainty);
1685: }
1686:
1687: public function toAbsoluteNumber(): Type
1688: {
1689: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toAbsoluteNumber());
1690:
1691: return $type;
1692: }
1693:
1694: public function toString(): Type
1695: {
1696: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toString());
1697:
1698: return $type;
1699: }
1700:
1701: public function toInteger(): Type
1702: {
1703: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toInteger());
1704:
1705: return $type;
1706: }
1707:
1708: public function toFloat(): Type
1709: {
1710: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toFloat());
1711:
1712: return $type;
1713: }
1714:
1715: public function toArray(): Type
1716: {
1717: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toArray());
1718:
1719: return $type;
1720: }
1721:
1722: public function toArrayKey(): Type
1723: {
1724: if ($this->isDecimalIntegerString()->yes()) {
1725: return new IntegerType();
1726: }
1727:
1728: if ($this->isNumericString()->yes()) {
1729: return TypeCombinator::union(
1730: new IntegerType(),
1731: $this,
1732: );
1733: }
1734:
1735: if ($this->isString()->yes()) {
1736: return $this;
1737: }
1738:
1739: return $this->intersectTypes(static fn (Type $type): Type => $type->toArrayKey());
1740: }
1741:
1742: public function toCoercedArgumentType(bool $strictTypes): Type
1743: {
1744: return $this->intersectTypes(static fn (Type $type): Type => $type->toCoercedArgumentType($strictTypes));
1745: }
1746:
1747: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1748: {
1749: $types = TemplateTypeMap::createEmpty();
1750:
1751: foreach ($this->types as $type) {
1752: $types = $types->intersect($type->inferTemplateTypes($receivedType));
1753: }
1754:
1755: return $types;
1756: }
1757:
1758: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1759: {
1760: $references = [];
1761:
1762: foreach ($this->types as $type) {
1763: foreach ($type->getReferencedTemplateTypes($positionVariance) as $reference) {
1764: $references[] = $reference;
1765: }
1766: }
1767:
1768: return $references;
1769: }
1770:
1771: public function traverse(callable $cb): Type
1772: {
1773: $types = [];
1774: $changed = false;
1775:
1776: foreach ($this->types as $type) {
1777: $newType = $cb($type);
1778: if ($type !== $newType) {
1779: $changed = true;
1780: }
1781: $types[] = $newType;
1782: }
1783:
1784: if ($changed) {
1785: return self::intersectOperands($types);
1786: }
1787:
1788: return $this;
1789: }
1790:
1791: public function traverseSimultaneously(Type $right, callable $cb): Type
1792: {
1793: if ($this->isArray()->yes() && $right->isArray()->yes()) {
1794: $changed = false;
1795: $newTypes = [];
1796:
1797: foreach ($this->types as $innerType) {
1798: $newKeyType = $cb($innerType->getIterableKeyType(), $right->getIterableKeyType());
1799: $newValueType = $cb($innerType->getIterableValueType(), $right->getIterableValueType());
1800: if ($newKeyType === $innerType->getIterableKeyType() && $newValueType === $innerType->getIterableValueType()) {
1801: $newTypes[] = $innerType;
1802: continue;
1803: }
1804:
1805: $changed = true;
1806: $newTypes[] = TypeTraverser::map($innerType, static function (Type $type, callable $traverse) use ($innerType, $newKeyType, $newValueType): Type {
1807: if ($type === $innerType->getIterableKeyType()) {
1808: return $newKeyType;
1809: }
1810: if ($type === $innerType->getIterableValueType()) {
1811: return $newValueType;
1812: }
1813:
1814: return $traverse($type);
1815: });
1816: }
1817:
1818: if (!$changed) {
1819: return $this;
1820: }
1821:
1822: return self::intersectOperands($newTypes);
1823: }
1824:
1825: return $this;
1826: }
1827:
1828: public function tryRemove(Type $typeToRemove): ?Type
1829: {
1830: $removedTypes = [];
1831: $changed = false;
1832: foreach ($this->types as $type) {
1833: $removed = TypeCombinator::remove($type, $typeToRemove);
1834: if (!$removed->equals($type)) {
1835: $changed = true;
1836: }
1837: $removedTypes[] = $removed;
1838: }
1839:
1840: // no member changed, so neither does the intersection - intersecting
1841: // the same members again would only re-reduce every pair of them
1842: if (!$changed) {
1843: return $this;
1844: }
1845:
1846: return self::intersectOperands($removedTypes);
1847: }
1848:
1849: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
1850: {
1851: // a member that errors decides for the value; intersecting an ErrorType,
1852: // a MixedType, with the other members' results would hide it
1853: $results = [];
1854: foreach ($this->types as $type) {
1855: $result = $type->arithmeticPower($exponent, $phpVersion);
1856: if ($result instanceof ErrorType) {
1857: return $result;
1858: }
1859: $results[] = $result;
1860: }
1861:
1862: return self::intersectOperands($results);
1863: }
1864:
1865: public function getFiniteTypes(): array
1866: {
1867: $first = null;
1868: $others = [];
1869: foreach ($this->types as $type) {
1870: $indexed = self::indexFiniteTypes($type->getFiniteTypes());
1871: if ($first === null) {
1872: $first = $indexed;
1873: continue;
1874: }
1875:
1876: $others[] = $indexed;
1877: }
1878:
1879: if ($first === null) {
1880: return [];
1881: }
1882:
1883: $result = [];
1884: foreach ($first as $key => $finiteType) {
1885: foreach ($others as $other) {
1886: if (is_string($key) ? !array_key_exists($key, $other) : !self::hasFiniteType($other, null, $finiteType)) {
1887: continue 2;
1888: }
1889: }
1890:
1891: $result[] = $finiteType;
1892: }
1893:
1894: if (count($result) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1895: return [];
1896: }
1897:
1898: return $result;
1899: }
1900:
1901: /**
1902: * The finite types of one member, one per value, in their order: keyed by
1903: * FiniteTypeSet::key(), which never keys by a number, and the values it
1904: * does not key (floats, constant arrays) by a list position, deduplicated
1905: * by equals().
1906: *
1907: * @param list<Type> $finiteTypes
1908: * @return array<int|string, Type>
1909: */
1910: private static function indexFiniteTypes(array $finiteTypes): array
1911: {
1912: $indexed = [];
1913: foreach ($finiteTypes as $finiteType) {
1914: $key = FiniteTypeSet::key($finiteType);
1915: if ($key !== null) {
1916: $indexed[$key] = $finiteType;
1917: continue;
1918: }
1919:
1920: foreach ($indexed as $existingKey => $existing) {
1921: if (is_int($existingKey) && $existing->equals($finiteType)) {
1922: $indexed[$existingKey] = $finiteType;
1923: continue 2;
1924: }
1925: }
1926:
1927: $indexed[] = $finiteType;
1928: }
1929:
1930: return $indexed;
1931: }
1932:
1933: /**
1934: * @param array<int|string, Type> $indexed
1935: * @param string|null $key the FiniteTypeSet::key() of $finiteType
1936: */
1937: private static function hasFiniteType(array $indexed, ?string $key, Type $finiteType): bool
1938: {
1939: if ($key !== null) {
1940: return array_key_exists($key, $indexed);
1941: }
1942:
1943: foreach ($indexed as $otherKey => $other) {
1944: if (is_int($otherKey) && $other->equals($finiteType)) {
1945: return true;
1946: }
1947: }
1948:
1949: return false;
1950: }
1951:
1952: /**
1953: * @param callable(Type $type): TrinaryLogic $getResult
1954: * @param (callable(Type $type): bool)|null $filter
1955: */
1956: private function intersectResults(
1957: callable $getResult,
1958: ?callable $filter = null,
1959: ): TrinaryLogic
1960: {
1961: $types = $this->types;
1962: if ($filter !== null) {
1963: $types = array_filter($types, $filter);
1964: }
1965: if (count($types) === 0) {
1966: return TrinaryLogic::createNo();
1967: }
1968:
1969: return TrinaryLogic::lazyMaxMin($types, $getResult);
1970: }
1971:
1972: /**
1973: * @param callable(Type $type): Type $getType
1974: */
1975: private function intersectTypes(callable $getType): Type
1976: {
1977: return self::intersectOperands(array_map($getType, $this->types));
1978: }
1979:
1980: /**
1981: * The intersection of the members after they were mapped. All of them at once
1982: * costs one pairwise reduction; folding them two at a time re-reduces the
1983: * growing intersection at every step, which is cubic in the member count.
1984: * Only two or more unions need the fold - distributing each over the others
1985: * at once multiplies their sizes.
1986: *
1987: * @param list<Type> $operands
1988: */
1989: private static function intersectOperands(array $operands): Type
1990: {
1991: $unionCount = 0;
1992: foreach ($operands as $operand) {
1993: if (!$operand instanceof UnionType) {
1994: continue;
1995: }
1996: $unionCount++;
1997: }
1998: if ($unionCount < 2) {
1999: return TypeCombinator::intersect(...$operands);
2000: }
2001:
2002: $result = $operands[0];
2003: for ($i = 1, $count = count($operands); $i < $count; $i++) {
2004: $result = TypeCombinator::intersect($result, $operands[$i]);
2005: }
2006: return $result;
2007: }
2008:
2009: /**
2010: * @param callable(Type $type): Type $getType
2011: */
2012: private function intersectTypesPreserveTemplateType(callable $getType): Type
2013: {
2014: return $this->intersectTypes(static function (Type $type) use ($getType): Type {
2015: if ($type instanceof TemplateType) {
2016: return $type;
2017: }
2018: return $getType($type);
2019: });
2020: }
2021:
2022: public function toPhpDocNode(): TypeNode
2023: {
2024: $baseTypes = [];
2025: $typesToDescribe = [];
2026: $skipTypeNames = [];
2027:
2028: $nonEmptyStr = false;
2029: $nonFalsyStr = false;
2030: $isList = $this->isList()->yes();
2031: $isArray = $this->isArray()->yes();
2032: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
2033: $describedTypes = [];
2034: $arrayPrintsArrayAccessories = false;
2035: foreach ($this->types as $type) {
2036: if (!$type instanceof ArrayType && !$type instanceof ConstantArrayType) {
2037: continue;
2038: }
2039:
2040: $arrayPrintsArrayAccessories = true;
2041: }
2042:
2043: foreach ($this->getSortedTypes() as $i => $type) {
2044: if ($type instanceof AccessoryNonEmptyStringType
2045: || $type instanceof AccessoryLiteralStringType
2046: || $type instanceof AccessoryNumericStringType
2047: || $type instanceof AccessoryNonFalsyStringType
2048: || $type instanceof AccessoryLowercaseStringType
2049: || $type instanceof AccessoryUppercaseStringType
2050: || $type instanceof AccessoryDecimalIntegerStringType
2051: ) {
2052: if ($type instanceof AccessoryNonFalsyStringType) {
2053: $nonFalsyStr = true;
2054: }
2055: if ($type instanceof AccessoryNonEmptyStringType) {
2056: $nonEmptyStr = true;
2057: }
2058: if ($nonEmptyStr && $nonFalsyStr) {
2059: // prevent redundant 'non-empty-string&non-falsy-string'
2060: foreach ($typesToDescribe as $key => $typeToDescribe) {
2061: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
2062: continue;
2063: }
2064:
2065: unset($typesToDescribe[$key]);
2066: }
2067: }
2068:
2069: $typesToDescribe[$i] = $type;
2070: $skipTypeNames[] = 'string';
2071: continue;
2072: }
2073:
2074: if ($isList || $isArray) {
2075: if ($type instanceof ArrayType) {
2076: $keyType = $type->getKeyType();
2077: $valueType = $type->getItemType();
2078: if ($isList) {
2079: $isMixedValueType = MixedType::isBareMixed($valueType, VerbosityLevel::value()) && !$valueType->isExplicitMixed();
2080: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-list' : 'list');
2081: if (!$isMixedValueType) {
2082: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2083: $valueType->toPhpDocNode(),
2084: ]);
2085: } else {
2086: $describedTypes[$i] = $identifierTypeNode;
2087: }
2088: } else {
2089: $isMixedKeyType = MixedType::isBareMixed($keyType, VerbosityLevel::value()) && !$keyType->isExplicitMixed();
2090: $isMixedValueType = MixedType::isBareMixed($valueType, VerbosityLevel::value()) && !$valueType->isExplicitMixed();
2091: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-array' : 'array');
2092: if (!$isMixedKeyType) {
2093: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2094: $keyType->toPhpDocNode(),
2095: $valueType->toPhpDocNode(),
2096: ]);
2097: } elseif (!$isMixedValueType) {
2098: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2099: $valueType->toPhpDocNode(),
2100: ]);
2101: } else {
2102: $describedTypes[$i] = $identifierTypeNode;
2103: }
2104: }
2105: continue;
2106: } elseif ($type instanceof ConstantArrayType) {
2107: $constantArrayTypeNode = $type->toPhpDocNode();
2108: if ($constantArrayTypeNode instanceof ArrayShapeNode) {
2109: $newKind = $constantArrayTypeNode->kind;
2110: if ($isList) {
2111: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
2112: $newKind = ArrayShapeNode::KIND_NON_EMPTY_LIST;
2113: } else {
2114: $newKind = ArrayShapeNode::KIND_LIST;
2115: }
2116: } elseif ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
2117: $newKind = ArrayShapeNode::KIND_NON_EMPTY_ARRAY;
2118: }
2119:
2120: if ($newKind !== $constantArrayTypeNode->kind) {
2121: if ($constantArrayTypeNode->sealed) {
2122: $constantArrayTypeNode = ArrayShapeNode::createSealed($constantArrayTypeNode->items, $newKind);
2123: } else {
2124: $constantArrayTypeNode = ArrayShapeNode::createUnsealed($constantArrayTypeNode->items, $constantArrayTypeNode->unsealedType, $newKind);
2125: }
2126: }
2127:
2128: $describedTypes[$i] = $constantArrayTypeNode;
2129: continue;
2130: }
2131: }
2132: // an array or a shape prints them, a recursive type like `__recursive<…>&non-empty-array` does not
2133: if (($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) && $arrayPrintsArrayAccessories) {
2134: continue;
2135: }
2136: }
2137:
2138: if (!$type instanceof AccessoryType) {
2139: $baseTypes[$i] = $type;
2140: continue;
2141: }
2142:
2143: $accessoryPhpDocNode = $type->toPhpDocNode();
2144: if ($accessoryPhpDocNode instanceof IdentifierTypeNode && $accessoryPhpDocNode->name === '') {
2145: continue;
2146: }
2147:
2148: $typesToDescribe[$i] = $type;
2149: }
2150:
2151: foreach ($baseTypes as $i => $type) {
2152: $typeNode = $type->toPhpDocNode();
2153: if ($typeNode instanceof GenericTypeNode && $typeNode->type instanceof IdentifierTypeNode && $typeNode->type->name === 'array') {
2154: $nonEmpty = false;
2155: $typeName = 'array';
2156: foreach ($typesToDescribe as $j => $typeToDescribe) {
2157: if ($typeToDescribe instanceof AccessoryArrayListType) {
2158: $typeName = 'list';
2159: if (count($typeNode->genericTypes) > 1) {
2160: array_shift($typeNode->genericTypes);
2161: }
2162: } elseif ($typeToDescribe instanceof NonEmptyArrayType) {
2163: $nonEmpty = true;
2164: } else {
2165: continue;
2166: }
2167:
2168: unset($typesToDescribe[$j]);
2169: }
2170:
2171: if ($nonEmpty) {
2172: $typeName = 'non-empty-' . $typeName;
2173: }
2174:
2175: $describedTypes[$i] = new GenericTypeNode(
2176: new IdentifierTypeNode($typeName),
2177: $typeNode->genericTypes,
2178: );
2179: continue;
2180: }
2181:
2182: if ($typeNode instanceof IdentifierTypeNode && in_array($typeNode->name, $skipTypeNames, true)) {
2183: continue;
2184: }
2185:
2186: $describedTypes[$i] = $typeNode;
2187: }
2188:
2189: foreach ($typesToDescribe as $i => $typeToDescribe) {
2190: $describedTypes[$i] = $typeToDescribe->toPhpDocNode();
2191: }
2192:
2193: ksort($describedTypes);
2194:
2195: $describedTypes = array_values($describedTypes);
2196:
2197: if (count($describedTypes) === 1) {
2198: return $describedTypes[0];
2199: }
2200:
2201: if (count($describedTypes) === 0) {
2202: throw new ShouldNotHappenException(sprintf('Intersection consists of %s but there should be at least one base type.', implode('&', array_map(static fn (Type $type) => $type->describe(VerbosityLevel::precise()), $this->types))));
2203: }
2204:
2205: return new IntersectionTypeNode($describedTypes);
2206: }
2207:
2208: public function toNativePhpTypeNode(NativeTypePosition $position)
2209: {
2210: return NativePhpTypeNodeHelper::intersection($this, $position);
2211: }
2212:
2213: public function hasTemplateOrLateResolvableType(): bool
2214: {
2215: foreach ($this->types as $type) {
2216: if (!$type->hasTemplateOrLateResolvableType()) {
2217: continue;
2218: }
2219:
2220: return true;
2221: }
2222:
2223: return false;
2224: }
2225:
2226: public function hasUnresolvedTemplateArgumentType(): bool
2227: {
2228: foreach ($this->types as $type) {
2229: if ($type->hasUnresolvedTemplateArgumentType()) {
2230: return true;
2231: }
2232: }
2233:
2234: return false;
2235: }
2236:
2237: public function toValueSet(): ValueSet
2238: {
2239: $valueSet = ValueSet::createUnknown();
2240: foreach ($this->types as $type) {
2241: $valueSet = $valueSet->intersect($type->toValueSet());
2242: }
2243:
2244: return $valueSet;
2245: }
2246:
2247: public function tryUnion(Type $otherType): ?Type
2248: {
2249: return IntersectionAlgebra::tryUnion($this, $otherType);
2250: }
2251:
2252: public function tryIntersect(Type $otherType): ?Type
2253: {
2254: return null;
2255: }
2256:
2257: }
2258: