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 = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$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 carries the array refinement, we describe
503: // it via its own describe() (e.g. "T of array") rather than collapsing
504: // 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) {
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) {
565: $keyType = $type->getKeyType();
566: $valueType = $type->getItemType();
567: if ($isList) {
568: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
569: $valueTypeDescription = '';
570: if (!$isMixedValueType) {
571: $valueTypeDescription = sprintf('<%s>', $valueType->describe($level));
572: }
573:
574: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-list' : 'list') . $valueTypeDescription;
575: } else {
576: $isMixedKeyType = $keyType instanceof MixedType && $keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$keyType->isExplicitMixed();
577: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
578: $typeDescription = '';
579: if (!$isMixedKeyType) {
580: $typeDescription = sprintf('<%s, %s>', $keyType->describe($level), $valueType->describe($level));
581: } elseif (!$isMixedValueType) {
582: $typeDescription = sprintf('<%s>', $valueType->describe($level));
583: }
584:
585: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-array' : 'array') . $typeDescription;
586: }
587: continue;
588: } elseif ($type instanceof ConstantArrayType) {
589: $description = $type->describe($level);
590: $kind = str_starts_with($description, 'list') ? 'list' : 'array';
591: $descriptionWithoutKind = substr($description, strlen($kind));
592: $begin = $isList ? 'list' : 'array';
593: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
594: $begin = 'non-empty-' . $begin;
595: }
596:
597: $describedTypes[$i] = $begin . $descriptionWithoutKind;
598: continue;
599: }
600: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
601: if ($hasTemplateArray) {
602: $describedTypes[$i] = $type->describe($level);
603: }
604: continue;
605: }
606: }
607:
608: if ($type instanceof CallableType && $type->isCommonCallable()) {
609: $typesToDescribe[$i] = $type;
610: $skipTypeNames[] = 'object';
611: $skipTypeNames[] = 'string';
612: continue;
613: }
614:
615: if (!$type instanceof AccessoryType) {
616: $baseTypes[$i] = $type;
617: continue;
618: }
619:
620: if ($skipAccessoryTypes) {
621: continue;
622: }
623:
624: $typesToDescribe[$i] = $type;
625: }
626:
627: foreach ($baseTypes as $i => $type) {
628: $typeDescription = $type->describe($level);
629:
630: if (in_array($typeDescription, ['object', 'string'], true) && in_array($typeDescription, $skipTypeNames, true)) {
631: foreach ($typesToDescribe as $j => $typeToDescribe) {
632: if ($typeToDescribe instanceof CallableType && $typeToDescribe->isCommonCallable()) {
633: $describedTypes[$i] = 'callable-' . $typeDescription;
634: unset($typesToDescribe[$j]);
635: continue 2;
636: }
637: }
638: }
639:
640: if (in_array($typeDescription, $skipTypeNames, true)) {
641: continue;
642: }
643:
644: $describedTypes[$i] = $type->describe($level);
645: }
646:
647: foreach ($typesToDescribe as $i => $typeToDescribe) {
648: $describedTypes[$i] = $typeToDescribe->describe($level);
649: }
650:
651: ksort($describedTypes);
652:
653: return implode('&', $describedTypes);
654: }
655:
656: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
657: {
658: return $this->intersectTypes(static fn (Type $type): Type => $type->getTemplateType($ancestorClassName, $templateTypeName));
659: }
660:
661: public function isObject(): TrinaryLogic
662: {
663: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isObject());
664: }
665:
666: public function getClassStringType(): Type
667: {
668: return $this->intersectTypes(static fn (Type $type): Type => $type->getClassStringType());
669: }
670:
671: public function isEnum(): TrinaryLogic
672: {
673: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isEnum());
674: }
675:
676: public function canAccessProperties(): TrinaryLogic
677: {
678: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessProperties());
679: }
680:
681: public function hasProperty(string $propertyName): TrinaryLogic
682: {
683: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasProperty($propertyName));
684: }
685:
686: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
687: {
688: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
689: }
690:
691: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
692: {
693: $propertyPrototypes = [];
694: foreach ($this->types as $type) {
695: if (!$type->hasProperty($propertyName)->yes()) {
696: continue;
697: }
698:
699: $propertyPrototypes[] = $type->getUnresolvedPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
700: }
701:
702: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
703: }
704:
705: public function hasInstanceProperty(string $propertyName): TrinaryLogic
706: {
707: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasInstanceProperty($propertyName));
708: }
709:
710: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
711: {
712: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
713: }
714:
715: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
716: {
717: $propertyPrototypes = [];
718: foreach ($this->types as $type) {
719: if (!$type->hasInstanceProperty($propertyName)->yes()) {
720: continue;
721: }
722:
723: $propertyPrototypes[] = $type->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->withFechedOnType($this);
724: }
725:
726: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
727: }
728:
729: public function hasStaticProperty(string $propertyName): TrinaryLogic
730: {
731: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasStaticProperty($propertyName));
732: }
733:
734: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
735: {
736: return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty();
737: }
738:
739: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
740: {
741: $propertyPrototypes = [];
742: foreach ($this->types as $type) {
743: if (!$type->hasStaticProperty($propertyName)->yes()) {
744: continue;
745: }
746:
747: $propertyPrototypes[] = $type->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
748: }
749:
750: return $this->createUnresolvedPropertyPrototype($propertyName, $propertyPrototypes);
751: }
752:
753: /**
754: * @param list<UnresolvedPropertyPrototypeReflection> $propertyPrototypes
755: */
756: private function createUnresolvedPropertyPrototype(string $propertyName, array $propertyPrototypes): UnresolvedPropertyPrototypeReflection
757: {
758: // a member like T of mixed has every property only as a placeholder,
759: // it must not override the property declared by another member
760: $declaredPropertyPrototypes = array_values(array_filter(
761: $propertyPrototypes,
762: static fn (UnresolvedPropertyPrototypeReflection $prototype): bool => !$prototype->getNakedProperty() instanceof DummyPropertyReflection,
763: ));
764: if (count($declaredPropertyPrototypes) > 0) {
765: $propertyPrototypes = $declaredPropertyPrototypes;
766: }
767:
768: $propertiesCount = count($propertyPrototypes);
769: if ($propertiesCount === 0) {
770: throw new MissingPropertyFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $propertyName);
771: }
772:
773: if ($propertiesCount === 1) {
774: return $propertyPrototypes[0];
775: }
776:
777: return new IntersectionTypeUnresolvedPropertyPrototypeReflection($propertyPrototypes);
778: }
779:
780: public function canCallMethods(): TrinaryLogic
781: {
782: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canCallMethods());
783: }
784:
785: public function hasMethod(string $methodName): TrinaryLogic
786: {
787: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasMethod($methodName));
788: }
789:
790: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
791: {
792: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
793: }
794:
795: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
796: {
797: $methodPrototypes = [];
798: foreach ($this->types as $type) {
799: if (!$type->hasMethod($methodName)->yes()) {
800: continue;
801: }
802:
803: $methodPrototypes[] = $type->getUnresolvedMethodPrototype($methodName, $scope)->withCalledOnType($this);
804: }
805:
806: // a member like T of mixed has every method only as a placeholder,
807: // it must not override the method declared by another member
808: $declaredMethodPrototypes = array_values(array_filter(
809: $methodPrototypes,
810: static fn (UnresolvedMethodPrototypeReflection $prototype): bool => !$prototype->getNakedMethod() instanceof DummyMethodReflection,
811: ));
812: if (count($declaredMethodPrototypes) > 0) {
813: $methodPrototypes = $declaredMethodPrototypes;
814: }
815:
816: $methodsCount = count($methodPrototypes);
817: if ($methodsCount === 0) {
818: throw new MissingMethodFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $methodName);
819: }
820:
821: if ($methodsCount === 1) {
822: return $methodPrototypes[0];
823: }
824:
825: return new IntersectionTypeUnresolvedMethodPrototypeReflection($methodName, $methodPrototypes);
826: }
827:
828: public function canAccessConstants(): TrinaryLogic
829: {
830: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessConstants());
831: }
832:
833: public function hasConstant(string $constantName): TrinaryLogic
834: {
835: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasConstant($constantName));
836: }
837:
838: public function getConstant(string $constantName): ClassConstantReflection
839: {
840: $dummyConstant = null;
841: foreach ($this->types as $type) {
842: if (!$type->hasConstant($constantName)->yes()) {
843: continue;
844: }
845:
846: $constant = $type->getConstant($constantName);
847:
848: // a member like T of mixed has every constant only as a placeholder,
849: // it must not override the constant declared by another member
850: if ($constant instanceof DummyClassConstantReflection) {
851: $dummyConstant ??= $constant;
852: continue;
853: }
854:
855: return $constant;
856: }
857:
858: if ($dummyConstant !== null) {
859: return $dummyConstant;
860: }
861:
862: throw new MissingConstantFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $constantName);
863: }
864:
865: public function isIterable(): TrinaryLogic
866: {
867: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isIterable());
868: }
869:
870: public function isIterableAtLeastOnce(): TrinaryLogic
871: {
872: return $this->isIterableAtLeastOnce ??= $this->isCallable()->yes() && $this->isArray()->yes()
873: ? TrinaryLogic::createYes()
874: : $this->intersectResults(
875: static fn (Type $type): TrinaryLogic => $type->isIterableAtLeastOnce(),
876: static fn (Type $type): bool => !$type->isIterable()->no(),
877: );
878: }
879:
880: public function getArraySize(): Type
881: {
882: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
883: return new ConstantIntegerType(2);
884: }
885:
886: $arraySize = $this->intersectTypes(static fn (Type $type): Type => $type->getArraySize());
887:
888: $knownOffsets = [];
889: foreach ($this->types as $type) {
890: if (!($type instanceof HasOffsetValueType) && !($type instanceof HasOffsetType)) {
891: continue;
892: }
893:
894: $knownOffsets[$type->getOffsetType()->getValue()] = true;
895: }
896:
897: if ($this->isList()->yes() && $this->isIterableAtLeastOnce()->yes()) {
898: $knownOffsets[0] = true;
899: }
900:
901: if ($knownOffsets !== []) {
902: return TypeCombinator::intersect($arraySize, IntegerRangeType::fromInterval(count($knownOffsets), null));
903: }
904:
905: return $arraySize;
906: }
907:
908: public function getIterableKeyType(): Type
909: {
910: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
911: return new UnionType([new ConstantIntegerType(0), new ConstantIntegerType(1)]);
912: }
913: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType());
914: }
915:
916: public function getFirstIterableKeyType(): Type
917: {
918: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType());
919: }
920:
921: public function getLastIterableKeyType(): Type
922: {
923: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType());
924: }
925:
926: public function getIterableValueType(): Type
927: {
928: $result = $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType());
929: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
930: return TypeCombinator::intersect(
931: $result,
932: new UnionType([
933: new ObjectWithoutClassType(),
934: new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]),
935: ]),
936: );
937: }
938: return $result;
939: }
940:
941: public function getFirstIterableValueType(): Type
942: {
943: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType());
944: }
945:
946: public function getLastIterableValueType(): Type
947: {
948: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType());
949: }
950:
951: public function isArray(): TrinaryLogic
952: {
953: return $this->isArray ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isArray());
954: }
955:
956: public function isConstantArray(): TrinaryLogic
957: {
958: return $this->isConstantArray ??= $this->isCallable()->yes() && $this->isArray()->yes()
959: ? TrinaryLogic::createYes()
960: : $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantArray());
961: }
962:
963: public function isOversizedArray(): TrinaryLogic
964: {
965: return $this->isOversizedArray ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOversizedArray());
966: }
967:
968: public function isList(): TrinaryLogic
969: {
970: return $this->isList ??= $this->isCallable()->yes() && $this->isArray()->yes()
971: ? TrinaryLogic::createYes()
972: : $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isList());
973: }
974:
975: public function isString(): TrinaryLogic
976: {
977: return $this->isString ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isString());
978: }
979:
980: public function isNumericString(): TrinaryLogic
981: {
982: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNumericString());
983: }
984:
985: public function isDecimalIntegerString(): TrinaryLogic
986: {
987: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isDecimalIntegerString());
988: }
989:
990: public function isNonEmptyString(): TrinaryLogic
991: {
992: if ($this->isCallable()->yes() && $this->isString()->yes()) {
993: return TrinaryLogic::createYes();
994: }
995: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonEmptyString());
996: }
997:
998: public function isNonFalsyString(): TrinaryLogic
999: {
1000: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonFalsyString());
1001: }
1002:
1003: public function isLiteralString(): TrinaryLogic
1004: {
1005: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLiteralString());
1006: }
1007:
1008: public function isLowercaseString(): TrinaryLogic
1009: {
1010: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLowercaseString());
1011: }
1012:
1013: public function isUppercaseString(): TrinaryLogic
1014: {
1015: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isUppercaseString());
1016: }
1017:
1018: public function isClassString(): TrinaryLogic
1019: {
1020: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isClassString());
1021: }
1022:
1023: public function getClassStringObjectType(): Type
1024: {
1025: return $this->intersectTypes(static fn (Type $type): Type => $type->getClassStringObjectType());
1026: }
1027:
1028: public function getObjectTypeOrClassStringObjectType(): Type
1029: {
1030: return $this->intersectTypes(static fn (Type $type): Type => $type->getObjectTypeOrClassStringObjectType());
1031: }
1032:
1033: public function isVoid(): TrinaryLogic
1034: {
1035: return TrinaryLogic::createNo();
1036: }
1037:
1038: public function isScalar(): TrinaryLogic
1039: {
1040: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isScalar());
1041: }
1042:
1043: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1044: {
1045: return $this->intersectResults(
1046: static fn (Type $innerType): TrinaryLogic => $innerType->looseCompare($type, $phpVersion)->toTrinaryLogic(),
1047: )->toBooleanType();
1048: }
1049:
1050: public function isOffsetAccessible(): TrinaryLogic
1051: {
1052: return $this->isOffsetAccessible ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessible());
1053: }
1054:
1055: public function isOffsetAccessLegal(): TrinaryLogic
1056: {
1057: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessLegal());
1058: }
1059:
1060: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1061: {
1062: $cacheKey = $offsetType->describe(VerbosityLevel::cache());
1063: if (isset($this->cachedHasOffsetValueType[$cacheKey])) {
1064: return $this->cachedHasOffsetValueType[$cacheKey];
1065: }
1066: return $this->cachedHasOffsetValueType[$cacheKey] = $this->doHasOffsetValueType($offsetType);
1067: }
1068:
1069: private function doHasOffsetValueType(Type $offsetType): TrinaryLogic
1070: {
1071: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
1072: $arrayKeyOffsetType = $offsetType->toArrayKey();
1073: $callableArrayOffsetType = new UnionType([new ConstantIntegerType(0), new ConstantIntegerType(1)]);
1074:
1075: return $callableArrayOffsetType->isSuperTypeOf($arrayKeyOffsetType)->result;
1076: }
1077:
1078: if ($this->isList()->yes()) {
1079: $arrayKeyOffsetType = $offsetType->toArrayKey();
1080:
1081: $negative = IntegerRangeType::fromInterval(null, -1);
1082: if ($negative->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1083: return TrinaryLogic::createNo();
1084: }
1085:
1086: $size = $this->getArraySize();
1087: if ($size instanceof IntegerRangeType && $size->getMin() !== null) {
1088: $knownOffsets = IntegerRangeType::fromInterval(0, $size->getMin() - 1);
1089: } elseif ($size instanceof ConstantIntegerType) {
1090: $knownOffsets = IntegerRangeType::fromInterval(0, $size->getValue() - 1);
1091: } elseif ($this->isIterableAtLeastOnce()->yes()) {
1092: $knownOffsets = new ConstantIntegerType(0);
1093: } else {
1094: $knownOffsets = null;
1095: }
1096:
1097: if ($knownOffsets !== null && $knownOffsets->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1098: return TrinaryLogic::createYes();
1099: }
1100:
1101: foreach ($this->types as $type) {
1102: if (!$type instanceof HasOffsetValueType && !$type instanceof HasOffsetType) {
1103: continue;
1104: }
1105:
1106: foreach ($type->getOffsetType()->getConstantScalarValues() as $constantScalarValue) {
1107: if (!is_int($constantScalarValue)) {
1108: continue;
1109: }
1110: if (IntegerRangeType::fromInterval(0, $constantScalarValue)->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1111: return TrinaryLogic::createYes();
1112: }
1113: }
1114: }
1115: }
1116:
1117: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasOffsetValueType($offsetType));
1118: }
1119:
1120: public function getOffsetValueType(Type $offsetType): Type
1121: {
1122: $cacheKey = $offsetType->describe(VerbosityLevel::cache());
1123: if (isset($this->cachedGetOffsetValueType[$cacheKey])) {
1124: return $this->cachedGetOffsetValueType[$cacheKey];
1125: }
1126: return $this->cachedGetOffsetValueType[$cacheKey] = $this->doGetOffsetValueType($offsetType);
1127: }
1128:
1129: private function doGetOffsetValueType(Type $offsetType): Type
1130: {
1131: $result = $this->intersectTypes(static fn (Type $type): Type => $type->getOffsetValueType($offsetType));
1132: if ($this->isOversizedArray()->yes()) {
1133: return TypeUtils::toBenevolentUnion($result);
1134: }
1135:
1136: if ($this->isCallable()->yes() && $this->isArray()->yes()) {
1137: $arrayKeyOffsetType = $offsetType->toArrayKey();
1138: if ((new ConstantIntegerType(0))->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1139: $narrowedType = new UnionType([new ClassStringType(), new ObjectWithoutClassType()]);
1140: } elseif ((new ConstantIntegerType(1))->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
1141: $narrowedType = new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]);
1142: } else {
1143: $narrowedType = new UnionType([new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]), new ObjectWithoutClassType()]);
1144: }
1145: $result = TypeCombinator::intersect($result, $narrowedType);
1146: }
1147:
1148: return $result;
1149: }
1150:
1151: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1152: {
1153: if ($this->isOversizedArray()->yes()) {
1154: return $this->intersectTypes(static function (Type $type) use ($offsetType, $valueType, $unionValues): Type {
1155: // avoid new HasOffsetValueType being intersected with oversized array
1156: if (!$type instanceof ArrayType) {
1157: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
1158: }
1159:
1160: if (!$offsetType instanceof ConstantStringType && !$offsetType instanceof ConstantIntegerType) {
1161: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
1162: }
1163:
1164: if (!$offsetType->isSuperTypeOf($type->getKeyType())->yes()) {
1165: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
1166: }
1167:
1168: return new IntersectionType([
1169: new ArrayType(
1170: TypeCombinator::union($type->getKeyType(), $offsetType),
1171: TypeCombinator::union($type->getItemType(), $valueType),
1172: ),
1173: new NonEmptyArrayType(),
1174: ]);
1175: });
1176: }
1177:
1178: $result = $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType, $unionValues));
1179:
1180: if (
1181: $offsetType !== null
1182: && $this->isList()->yes()
1183: && !$result->isList()->yes()
1184: ) {
1185: if ($this->isIterableAtLeastOnce()->yes() && (new ConstantIntegerType(1))->isSuperTypeOf($offsetType)->yes()) {
1186: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1187: } else {
1188: foreach ($this->types as $type) {
1189: if (!$type instanceof HasOffsetValueType && !$type instanceof HasOffsetType) {
1190: continue;
1191: }
1192:
1193: foreach ($type->getOffsetType()->getConstantScalarValues() as $constantScalarValue) {
1194: if (!is_int($constantScalarValue)) {
1195: continue;
1196: }
1197: // no offset exists past PHP_INT_MAX: the list may grow up to it
1198: $maxListOffset = $constantScalarValue < PHP_INT_MAX ? $constantScalarValue + 1 : null;
1199: if (IntegerRangeType::fromInterval(0, $maxListOffset)->isSuperTypeOf($offsetType)->yes()) {
1200: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1201: break 2;
1202: }
1203: }
1204: }
1205: }
1206: }
1207:
1208: if (
1209: $this->isList()->yes()
1210: && $offsetType !== null
1211: && $offsetType->toArrayKey()->isInteger()->yes()
1212: && $this->getIterableValueType()->isArray()->yes()
1213: ) {
1214: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
1215: }
1216:
1217: return $result;
1218: }
1219:
1220: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1221: {
1222: return $this->intersectTypes(static fn (Type $type): Type => $type->setExistingOffsetValueType($offsetType, $valueType));
1223: }
1224:
1225: public function unsetOffset(Type $offsetType): Type
1226: {
1227: return $this->intersectTypes(static fn (Type $type): Type => $type->unsetOffset($offsetType));
1228: }
1229:
1230: public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
1231: {
1232: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArrayFiltered($filterValueType, $strict));
1233: }
1234:
1235: public function getKeysArray(): Type
1236: {
1237: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArray());
1238: }
1239:
1240: public function getValuesArray(): Type
1241: {
1242: $cb = static fn (Type $type): Type => $type->getValuesArray();
1243: if ($this->isList()->yes()) {
1244: return $this;
1245: }
1246: return $this->intersectTypes($cb);
1247: }
1248:
1249: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
1250: {
1251: return $this->intersectTypes(static fn (Type $type): Type => $type->chunkArray($lengthType, $preserveKeys));
1252: }
1253:
1254: public function fillKeysArray(Type $valueType): Type
1255: {
1256: return $this->intersectTypes(static fn (Type $type): Type => $type->fillKeysArray($valueType));
1257: }
1258:
1259: public function flipArray(): Type
1260: {
1261: return $this->intersectTypes(static fn (Type $type): Type => $type->flipArray());
1262: }
1263:
1264: public function intersectKeyArray(Type $otherArraysType): Type
1265: {
1266: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->intersectKeyArray($otherArraysType));
1267: }
1268:
1269: public function popArray(): Type
1270: {
1271: if ($this->isList()->yes()) {
1272: // hasOffsetValue(n, T) on a list proves indices 0..n exist; popping
1273: // removes the highest index, so offsets up to n - 1 survive. Their
1274: // values are unknown - the value known at n may have been the popped one.
1275: $members = [];
1276: foreach ($this->types as $type) {
1277: if ($type instanceof TemplateType) {
1278: $members[] = $type;
1279: continue;
1280: }
1281: if ($type instanceof HasOffsetValueType || $type instanceof HasOffsetType) {
1282: $offsetType = $type->getOffsetType();
1283: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1284: $members[] = new HasOffsetType(new ConstantIntegerType($offsetType->getValue() - 1));
1285: }
1286: continue;
1287: }
1288: $members[] = $type->popArray();
1289: }
1290:
1291: return TypeCombinator::intersect(...$members);
1292: }
1293:
1294: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->popArray());
1295: }
1296:
1297: public function reverseArray(TrinaryLogic $preserveKeys): Type
1298: {
1299: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->reverseArray($preserveKeys));
1300: }
1301:
1302: public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Type
1303: {
1304: return $this->intersectTypes(static fn (Type $type): Type => $type->searchArray($needleType, $strict));
1305: }
1306:
1307: public function shiftArray(): Type
1308: {
1309: if ($this->isList()->yes()) {
1310: // shifting a list reindexes: index n's value always moves to n - 1
1311: $members = [];
1312: foreach ($this->types as $type) {
1313: if ($type instanceof TemplateType) {
1314: $members[] = $type;
1315: continue;
1316: }
1317: if ($type instanceof HasOffsetValueType) {
1318: $offsetType = $type->getOffsetType();
1319: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1320: $members[] = new HasOffsetValueType(new ConstantIntegerType($offsetType->getValue() - 1), $type->getValueType());
1321: }
1322: continue;
1323: }
1324: if ($type instanceof HasOffsetType) {
1325: $offsetType = $type->getOffsetType();
1326: if ($offsetType instanceof ConstantIntegerType && $offsetType->getValue() >= 1) {
1327: $members[] = new HasOffsetType(new ConstantIntegerType($offsetType->getValue() - 1));
1328: }
1329: continue;
1330: }
1331: $members[] = $type->shiftArray();
1332: }
1333:
1334: return TypeCombinator::intersect(...$members);
1335: }
1336:
1337: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->shiftArray());
1338: }
1339:
1340: public function shuffleArray(): Type
1341: {
1342: $cb = static fn (Type $type): Type => $type->shuffleArray();
1343: if ($this->isList()->yes()) {
1344: return $this->intersectTypesPreserveTemplateType($cb);
1345: }
1346: return $this->intersectTypes($cb);
1347: }
1348:
1349: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
1350: {
1351: $result = $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->sliceArray($offsetType, $lengthType, $preserveKeys));
1352:
1353: if (
1354: $this->isList()->yes()
1355: && $this->isIterableAtLeastOnce()->yes()
1356: && (new ConstantIntegerType(0))->isSuperTypeOf($offsetType)->yes()
1357: && IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($lengthType)->yes()
1358: ) {
1359: $result = TypeCombinator::intersect($result, new NonEmptyArrayType());
1360: }
1361:
1362: return $result;
1363: }
1364:
1365: public function spliceArray(Type $offsetType, Type $lengthType, Type $replacementType): Type
1366: {
1367: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->spliceArray($offsetType, $lengthType, $replacementType));
1368: }
1369:
1370: public function truncateListToSize(Type $sizeType): Type
1371: {
1372: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->truncateListToSize($sizeType));
1373: }
1374:
1375: public function makeListMaybe(): Type
1376: {
1377: return $this->intersectTypes(static fn (Type $type): Type => $type->makeListMaybe());
1378: }
1379:
1380: public function mapValueType(callable $cb): Type
1381: {
1382: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->mapValueType($cb));
1383: }
1384:
1385: public function mapKeyType(callable $cb): Type
1386: {
1387: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->mapKeyType($cb));
1388: }
1389:
1390: public function makeAllArrayKeysOptional(): Type
1391: {
1392: return $this->intersectTypes(static fn (Type $type): Type => $type->makeAllArrayKeysOptional());
1393: }
1394:
1395: public function changeKeyCaseArray(?int $case): Type
1396: {
1397: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->changeKeyCaseArray($case));
1398: }
1399:
1400: public function filterArrayRemovingFalsey(): Type
1401: {
1402: return $this->intersectTypesPreserveTemplateType(static fn (Type $type): Type => $type->filterArrayRemovingFalsey());
1403: }
1404:
1405: public function getEnumCases(): array
1406: {
1407: $compare = [];
1408: foreach ($this->types as $type) {
1409: $oneType = [];
1410: foreach ($type->getEnumCases() as $enumCase) {
1411: $oneType[$enumCase->getClassName() . '::' . $enumCase->getEnumCaseName()] = $enumCase;
1412: }
1413: $compare[] = $oneType;
1414: }
1415:
1416: return array_values(array_intersect_key(...$compare));
1417: }
1418:
1419: public function getEnumCaseObject(): ?EnumCaseObjectType
1420: {
1421: $singleCase = null;
1422: foreach ($this->types as $type) {
1423: $caseObject = $type->getEnumCaseObject();
1424: if ($caseObject === null) {
1425: continue;
1426: }
1427:
1428: if ($singleCase !== null) {
1429: return null;
1430: }
1431:
1432: $singleCase = $caseObject;
1433: }
1434:
1435: return $singleCase;
1436: }
1437:
1438: public function isCallable(): TrinaryLogic
1439: {
1440: return $this->isCallable ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCallable());
1441: }
1442:
1443: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1444: {
1445: $yesAcceptors = [];
1446:
1447: foreach ($this->types as $type) {
1448: if (!$type->isCallable()->yes()) {
1449: continue;
1450: }
1451: $yesAcceptors[] = $type->getCallableParametersAcceptors($scope);
1452: }
1453:
1454: if (count($yesAcceptors) === 0) {
1455: if ($this->isCallable()->no()) {
1456: throw new ShouldNotHappenException();
1457: }
1458:
1459: return [new TrivialParametersAcceptor()];
1460: }
1461:
1462: $result = [];
1463: $combinations = CombinationsHelper::combinations($yesAcceptors);
1464: foreach ($combinations as $combination) {
1465: $combined = ParametersAcceptorSelector::combineAcceptors($combination);
1466: if (!$combined instanceof CallableParametersAcceptor) {
1467: throw new ShouldNotHappenException();
1468: }
1469: $result[] = $combined;
1470: }
1471:
1472: return $result;
1473: }
1474:
1475: public function isCloneable(): TrinaryLogic
1476: {
1477: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCloneable());
1478: }
1479:
1480: public function isSmallerThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1481: {
1482: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThan($otherType, $phpVersion));
1483: }
1484:
1485: public function isSmallerThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1486: {
1487: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThanOrEqual($otherType, $phpVersion));
1488: }
1489:
1490: public function isNull(): TrinaryLogic
1491: {
1492: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNull());
1493: }
1494:
1495: public function isConstantValue(): TrinaryLogic
1496: {
1497: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantValue());
1498: }
1499:
1500: public function isConstantScalarValue(): TrinaryLogic
1501: {
1502: return $this->isConstantScalarValue ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantScalarValue());
1503: }
1504:
1505: public function getConstantScalarTypes(): array
1506: {
1507: $scalarTypes = [];
1508: foreach ($this->types as $type) {
1509: foreach ($type->getConstantScalarTypes() as $scalarType) {
1510: $scalarTypes[] = $scalarType;
1511: }
1512: }
1513:
1514: return $scalarTypes;
1515: }
1516:
1517: public function getConstantScalarValues(): array
1518: {
1519: $values = [];
1520: foreach ($this->types as $type) {
1521: foreach ($type->getConstantScalarValues() as $value) {
1522: $values[] = $value;
1523: }
1524: }
1525:
1526: return $values;
1527: }
1528:
1529: public function isTrue(): TrinaryLogic
1530: {
1531: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isTrue());
1532: }
1533:
1534: public function isFalse(): TrinaryLogic
1535: {
1536: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFalse());
1537: }
1538:
1539: public function isBoolean(): TrinaryLogic
1540: {
1541: return $this->isBoolean ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isBoolean());
1542: }
1543:
1544: public function isFloat(): TrinaryLogic
1545: {
1546: return $this->isFloat ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFloat());
1547: }
1548:
1549: public function isInteger(): TrinaryLogic
1550: {
1551: return $this->isInteger ??= $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isInteger());
1552: }
1553:
1554: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1555: {
1556: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThan($type, $phpVersion));
1557: }
1558:
1559: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1560: {
1561: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThanOrEqual($type, $phpVersion));
1562: }
1563:
1564: public function getSmallerType(PhpVersion $phpVersion): Type
1565: {
1566: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerType($phpVersion));
1567: }
1568:
1569: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
1570: {
1571: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerOrEqualType($phpVersion));
1572: }
1573:
1574: public function getGreaterType(PhpVersion $phpVersion): Type
1575: {
1576: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterType($phpVersion));
1577: }
1578:
1579: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
1580: {
1581: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterOrEqualType($phpVersion));
1582: }
1583:
1584: public function toBoolean(): BooleanType
1585: {
1586: $type = $this->intersectTypes(static fn (Type $type): BooleanType => $type->toBoolean());
1587:
1588: if (!$type instanceof BooleanType) {
1589: return new BooleanType();
1590: }
1591:
1592: return $type;
1593: }
1594:
1595: public function toNumber(): Type
1596: {
1597: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toNumber());
1598:
1599: return $type;
1600: }
1601:
1602: public function toBitwiseNotType(): Type
1603: {
1604: return $this->intersectTypes(static fn (Type $type): Type => $type->toBitwiseNotType());
1605: }
1606:
1607: public function toGetClassResultType(): Type
1608: {
1609: return $this->intersectTypes(static fn (Type $type): Type => $type->toGetClassResultType());
1610: }
1611:
1612: public function toClassConstantType(ReflectionProvider $reflectionProvider): Type
1613: {
1614: return $this->intersectTypes(static fn (Type $type): Type => $type->toClassConstantType($reflectionProvider));
1615: }
1616:
1617: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
1618: {
1619: $types = [];
1620: $uncertainty = false;
1621: foreach ($this->getTypes() as $innerType) {
1622: $result = $innerType->toObjectTypeForInstanceofCheck();
1623: $types[] = $result->type;
1624: if (!$result->uncertainty) {
1625: continue;
1626: }
1627:
1628: $uncertainty = true;
1629: }
1630:
1631: return new ClassNameToObjectTypeResult(TypeCombinator::intersect(...$types), $uncertainty);
1632: }
1633:
1634: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
1635: {
1636: $types = [];
1637: $uncertainty = false;
1638: foreach ($this->getTypes() as $innerType) {
1639: $result = $innerType->toObjectTypeForIsACheck($objectOrClassType, $allowString, $allowSameClass);
1640: $types[] = $result->type;
1641: if (!$result->uncertainty) {
1642: continue;
1643: }
1644:
1645: $uncertainty = true;
1646: }
1647:
1648: return new ClassNameToObjectTypeResult(TypeCombinator::intersect(...$types), $uncertainty);
1649: }
1650:
1651: public function toAbsoluteNumber(): Type
1652: {
1653: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toAbsoluteNumber());
1654:
1655: return $type;
1656: }
1657:
1658: public function toString(): Type
1659: {
1660: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toString());
1661:
1662: return $type;
1663: }
1664:
1665: public function toInteger(): Type
1666: {
1667: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toInteger());
1668:
1669: return $type;
1670: }
1671:
1672: public function toFloat(): Type
1673: {
1674: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toFloat());
1675:
1676: return $type;
1677: }
1678:
1679: public function toArray(): Type
1680: {
1681: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toArray());
1682:
1683: return $type;
1684: }
1685:
1686: public function toArrayKey(): Type
1687: {
1688: if ($this->isDecimalIntegerString()->yes()) {
1689: return new IntegerType();
1690: }
1691:
1692: if ($this->isNumericString()->yes()) {
1693: return TypeCombinator::union(
1694: new IntegerType(),
1695: $this,
1696: );
1697: }
1698:
1699: if ($this->isString()->yes()) {
1700: return $this;
1701: }
1702:
1703: return $this->intersectTypes(static fn (Type $type): Type => $type->toArrayKey());
1704: }
1705:
1706: public function toCoercedArgumentType(bool $strictTypes): Type
1707: {
1708: return $this->intersectTypes(static fn (Type $type): Type => $type->toCoercedArgumentType($strictTypes));
1709: }
1710:
1711: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1712: {
1713: $types = TemplateTypeMap::createEmpty();
1714:
1715: foreach ($this->types as $type) {
1716: $types = $types->intersect($type->inferTemplateTypes($receivedType));
1717: }
1718:
1719: return $types;
1720: }
1721:
1722: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1723: {
1724: $references = [];
1725:
1726: foreach ($this->types as $type) {
1727: foreach ($type->getReferencedTemplateTypes($positionVariance) as $reference) {
1728: $references[] = $reference;
1729: }
1730: }
1731:
1732: return $references;
1733: }
1734:
1735: public function traverse(callable $cb): Type
1736: {
1737: $types = [];
1738: $changed = false;
1739:
1740: foreach ($this->types as $type) {
1741: $newType = $cb($type);
1742: if ($type !== $newType) {
1743: $changed = true;
1744: }
1745: $types[] = $newType;
1746: }
1747:
1748: if ($changed) {
1749: return self::intersectOperands($types);
1750: }
1751:
1752: return $this;
1753: }
1754:
1755: public function traverseSimultaneously(Type $right, callable $cb): Type
1756: {
1757: if ($this->isArray()->yes() && $right->isArray()->yes()) {
1758: $changed = false;
1759: $newTypes = [];
1760:
1761: foreach ($this->types as $innerType) {
1762: $newKeyType = $cb($innerType->getIterableKeyType(), $right->getIterableKeyType());
1763: $newValueType = $cb($innerType->getIterableValueType(), $right->getIterableValueType());
1764: if ($newKeyType === $innerType->getIterableKeyType() && $newValueType === $innerType->getIterableValueType()) {
1765: $newTypes[] = $innerType;
1766: continue;
1767: }
1768:
1769: $changed = true;
1770: $newTypes[] = TypeTraverser::map($innerType, static function (Type $type, callable $traverse) use ($innerType, $newKeyType, $newValueType): Type {
1771: if ($type === $innerType->getIterableKeyType()) {
1772: return $newKeyType;
1773: }
1774: if ($type === $innerType->getIterableValueType()) {
1775: return $newValueType;
1776: }
1777:
1778: return $traverse($type);
1779: });
1780: }
1781:
1782: if (!$changed) {
1783: return $this;
1784: }
1785:
1786: return self::intersectOperands($newTypes);
1787: }
1788:
1789: return $this;
1790: }
1791:
1792: public function tryRemove(Type $typeToRemove): ?Type
1793: {
1794: $removedTypes = [];
1795: $changed = false;
1796: foreach ($this->types as $type) {
1797: $removed = TypeCombinator::remove($type, $typeToRemove);
1798: if (!$removed->equals($type)) {
1799: $changed = true;
1800: }
1801: $removedTypes[] = $removed;
1802: }
1803:
1804: // no member changed, so neither does the intersection - intersecting
1805: // the same members again would only re-reduce every pair of them
1806: if (!$changed) {
1807: return $this;
1808: }
1809:
1810: return self::intersectOperands($removedTypes);
1811: }
1812:
1813: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
1814: {
1815: // a member that errors decides for the value; intersecting an ErrorType,
1816: // a MixedType, with the other members' results would hide it
1817: $results = [];
1818: foreach ($this->types as $type) {
1819: $result = $type->arithmeticPower($exponent, $phpVersion);
1820: if ($result instanceof ErrorType) {
1821: return $result;
1822: }
1823: $results[] = $result;
1824: }
1825:
1826: return self::intersectOperands($results);
1827: }
1828:
1829: public function getFiniteTypes(): array
1830: {
1831: $first = null;
1832: $others = [];
1833: foreach ($this->types as $type) {
1834: $indexed = self::indexFiniteTypes($type->getFiniteTypes());
1835: if ($first === null) {
1836: $first = $indexed;
1837: continue;
1838: }
1839:
1840: $others[] = $indexed;
1841: }
1842:
1843: if ($first === null) {
1844: return [];
1845: }
1846:
1847: $result = [];
1848: foreach ($first as $key => $finiteType) {
1849: foreach ($others as $other) {
1850: if (is_string($key) ? !array_key_exists($key, $other) : !self::hasFiniteType($other, null, $finiteType)) {
1851: continue 2;
1852: }
1853: }
1854:
1855: $result[] = $finiteType;
1856: }
1857:
1858: if (count($result) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1859: return [];
1860: }
1861:
1862: return $result;
1863: }
1864:
1865: /**
1866: * The finite types of one member, one per value, in their order: keyed by
1867: * FiniteTypeSet::key(), which never keys by a number, and the values it
1868: * does not key (floats, constant arrays) by a list position, deduplicated
1869: * by equals().
1870: *
1871: * @param list<Type> $finiteTypes
1872: * @return array<int|string, Type>
1873: */
1874: private static function indexFiniteTypes(array $finiteTypes): array
1875: {
1876: $indexed = [];
1877: foreach ($finiteTypes as $finiteType) {
1878: $key = FiniteTypeSet::key($finiteType);
1879: if ($key !== null) {
1880: $indexed[$key] = $finiteType;
1881: continue;
1882: }
1883:
1884: foreach ($indexed as $existingKey => $existing) {
1885: if (is_int($existingKey) && $existing->equals($finiteType)) {
1886: $indexed[$existingKey] = $finiteType;
1887: continue 2;
1888: }
1889: }
1890:
1891: $indexed[] = $finiteType;
1892: }
1893:
1894: return $indexed;
1895: }
1896:
1897: /**
1898: * @param array<int|string, Type> $indexed
1899: * @param string|null $key the FiniteTypeSet::key() of $finiteType
1900: */
1901: private static function hasFiniteType(array $indexed, ?string $key, Type $finiteType): bool
1902: {
1903: if ($key !== null) {
1904: return array_key_exists($key, $indexed);
1905: }
1906:
1907: foreach ($indexed as $otherKey => $other) {
1908: if (is_int($otherKey) && $other->equals($finiteType)) {
1909: return true;
1910: }
1911: }
1912:
1913: return false;
1914: }
1915:
1916: /**
1917: * @param callable(Type $type): TrinaryLogic $getResult
1918: * @param (callable(Type $type): bool)|null $filter
1919: */
1920: private function intersectResults(
1921: callable $getResult,
1922: ?callable $filter = null,
1923: ): TrinaryLogic
1924: {
1925: $types = $this->types;
1926: if ($filter !== null) {
1927: $types = array_filter($types, $filter);
1928: }
1929: if (count($types) === 0) {
1930: return TrinaryLogic::createNo();
1931: }
1932:
1933: return TrinaryLogic::lazyMaxMin($types, $getResult);
1934: }
1935:
1936: /**
1937: * @param callable(Type $type): Type $getType
1938: */
1939: private function intersectTypes(callable $getType): Type
1940: {
1941: return self::intersectOperands(array_map($getType, $this->types));
1942: }
1943:
1944: /**
1945: * The intersection of the members after they were mapped. All of them at once
1946: * costs one pairwise reduction; folding them two at a time re-reduces the
1947: * growing intersection at every step, which is cubic in the member count.
1948: * Only two or more unions need the fold - distributing each over the others
1949: * at once multiplies their sizes.
1950: *
1951: * @param list<Type> $operands
1952: */
1953: private static function intersectOperands(array $operands): Type
1954: {
1955: $unionCount = 0;
1956: foreach ($operands as $operand) {
1957: if (!$operand instanceof UnionType) {
1958: continue;
1959: }
1960: $unionCount++;
1961: }
1962: if ($unionCount < 2) {
1963: return TypeCombinator::intersect(...$operands);
1964: }
1965:
1966: $result = $operands[0];
1967: for ($i = 1, $count = count($operands); $i < $count; $i++) {
1968: $result = TypeCombinator::intersect($result, $operands[$i]);
1969: }
1970: return $result;
1971: }
1972:
1973: /**
1974: * @param callable(Type $type): Type $getType
1975: */
1976: private function intersectTypesPreserveTemplateType(callable $getType): Type
1977: {
1978: return $this->intersectTypes(static function (Type $type) use ($getType): Type {
1979: if ($type instanceof TemplateType) {
1980: return $type;
1981: }
1982: return $getType($type);
1983: });
1984: }
1985:
1986: public function toPhpDocNode(): TypeNode
1987: {
1988: $baseTypes = [];
1989: $typesToDescribe = [];
1990: $skipTypeNames = [];
1991:
1992: $nonEmptyStr = false;
1993: $nonFalsyStr = false;
1994: $isList = $this->isList()->yes();
1995: $isArray = $this->isArray()->yes();
1996: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
1997: $describedTypes = [];
1998:
1999: foreach ($this->getSortedTypes() as $i => $type) {
2000: if ($type instanceof AccessoryNonEmptyStringType
2001: || $type instanceof AccessoryLiteralStringType
2002: || $type instanceof AccessoryNumericStringType
2003: || $type instanceof AccessoryNonFalsyStringType
2004: || $type instanceof AccessoryLowercaseStringType
2005: || $type instanceof AccessoryUppercaseStringType
2006: || $type instanceof AccessoryDecimalIntegerStringType
2007: ) {
2008: if ($type instanceof AccessoryNonFalsyStringType) {
2009: $nonFalsyStr = true;
2010: }
2011: if ($type instanceof AccessoryNonEmptyStringType) {
2012: $nonEmptyStr = true;
2013: }
2014: if ($nonEmptyStr && $nonFalsyStr) {
2015: // prevent redundant 'non-empty-string&non-falsy-string'
2016: foreach ($typesToDescribe as $key => $typeToDescribe) {
2017: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
2018: continue;
2019: }
2020:
2021: unset($typesToDescribe[$key]);
2022: }
2023: }
2024:
2025: $typesToDescribe[$i] = $type;
2026: $skipTypeNames[] = 'string';
2027: continue;
2028: }
2029:
2030: if ($isList || $isArray) {
2031: if ($type instanceof ArrayType) {
2032: $keyType = $type->getKeyType();
2033: $valueType = $type->getItemType();
2034: if ($isList) {
2035: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
2036: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-list' : 'list');
2037: if (!$isMixedValueType) {
2038: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2039: $valueType->toPhpDocNode(),
2040: ]);
2041: } else {
2042: $describedTypes[$i] = $identifierTypeNode;
2043: }
2044: } else {
2045: $isMixedKeyType = $keyType instanceof MixedType && $keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$keyType->isExplicitMixed();
2046: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
2047: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-array' : 'array');
2048: if (!$isMixedKeyType) {
2049: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2050: $keyType->toPhpDocNode(),
2051: $valueType->toPhpDocNode(),
2052: ]);
2053: } elseif (!$isMixedValueType) {
2054: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
2055: $valueType->toPhpDocNode(),
2056: ]);
2057: } else {
2058: $describedTypes[$i] = $identifierTypeNode;
2059: }
2060: }
2061: continue;
2062: } elseif ($type instanceof ConstantArrayType) {
2063: $constantArrayTypeNode = $type->toPhpDocNode();
2064: if ($constantArrayTypeNode instanceof ArrayShapeNode) {
2065: $newKind = $constantArrayTypeNode->kind;
2066: if ($isList) {
2067: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
2068: $newKind = ArrayShapeNode::KIND_NON_EMPTY_LIST;
2069: } else {
2070: $newKind = ArrayShapeNode::KIND_LIST;
2071: }
2072: } elseif ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
2073: $newKind = ArrayShapeNode::KIND_NON_EMPTY_ARRAY;
2074: }
2075:
2076: if ($newKind !== $constantArrayTypeNode->kind) {
2077: if ($constantArrayTypeNode->sealed) {
2078: $constantArrayTypeNode = ArrayShapeNode::createSealed($constantArrayTypeNode->items, $newKind);
2079: } else {
2080: $constantArrayTypeNode = ArrayShapeNode::createUnsealed($constantArrayTypeNode->items, $constantArrayTypeNode->unsealedType, $newKind);
2081: }
2082: }
2083:
2084: $describedTypes[$i] = $constantArrayTypeNode;
2085: continue;
2086: }
2087: }
2088: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
2089: continue;
2090: }
2091: }
2092:
2093: if (!$type instanceof AccessoryType) {
2094: $baseTypes[$i] = $type;
2095: continue;
2096: }
2097:
2098: $accessoryPhpDocNode = $type->toPhpDocNode();
2099: if ($accessoryPhpDocNode instanceof IdentifierTypeNode && $accessoryPhpDocNode->name === '') {
2100: continue;
2101: }
2102:
2103: $typesToDescribe[$i] = $type;
2104: }
2105:
2106: foreach ($baseTypes as $i => $type) {
2107: $typeNode = $type->toPhpDocNode();
2108: if ($typeNode instanceof GenericTypeNode && $typeNode->type instanceof IdentifierTypeNode && $typeNode->type->name === 'array') {
2109: $nonEmpty = false;
2110: $typeName = 'array';
2111: foreach ($typesToDescribe as $j => $typeToDescribe) {
2112: if ($typeToDescribe instanceof AccessoryArrayListType) {
2113: $typeName = 'list';
2114: if (count($typeNode->genericTypes) > 1) {
2115: array_shift($typeNode->genericTypes);
2116: }
2117: } elseif ($typeToDescribe instanceof NonEmptyArrayType) {
2118: $nonEmpty = true;
2119: } else {
2120: continue;
2121: }
2122:
2123: unset($typesToDescribe[$j]);
2124: }
2125:
2126: if ($nonEmpty) {
2127: $typeName = 'non-empty-' . $typeName;
2128: }
2129:
2130: $describedTypes[$i] = new GenericTypeNode(
2131: new IdentifierTypeNode($typeName),
2132: $typeNode->genericTypes,
2133: );
2134: continue;
2135: }
2136:
2137: if ($typeNode instanceof IdentifierTypeNode && in_array($typeNode->name, $skipTypeNames, true)) {
2138: continue;
2139: }
2140:
2141: $describedTypes[$i] = $typeNode;
2142: }
2143:
2144: foreach ($typesToDescribe as $i => $typeToDescribe) {
2145: $describedTypes[$i] = $typeToDescribe->toPhpDocNode();
2146: }
2147:
2148: ksort($describedTypes);
2149:
2150: $describedTypes = array_values($describedTypes);
2151:
2152: if (count($describedTypes) === 1) {
2153: return $describedTypes[0];
2154: }
2155:
2156: if (count($describedTypes) === 0) {
2157: 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))));
2158: }
2159:
2160: return new IntersectionTypeNode($describedTypes);
2161: }
2162:
2163: public function toNativePhpTypeNode(NativeTypePosition $position)
2164: {
2165: return NativePhpTypeNodeHelper::intersection($this, $position);
2166: }
2167:
2168: public function hasTemplateOrLateResolvableType(): bool
2169: {
2170: foreach ($this->types as $type) {
2171: if (!$type->hasTemplateOrLateResolvableType()) {
2172: continue;
2173: }
2174:
2175: return true;
2176: }
2177:
2178: return false;
2179: }
2180:
2181: public function toValueSet(): ValueSet
2182: {
2183: $valueSet = ValueSet::createUnknown();
2184: foreach ($this->types as $type) {
2185: $valueSet = $valueSet->intersect($type->toValueSet());
2186: }
2187:
2188: return $valueSet;
2189: }
2190:
2191: }
2192: