1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\Php\PhpVersion;
6: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
7: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
8: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
9: use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
10: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
11: use PHPStan\Reflection\ClassConstantReflection;
12: use PHPStan\Reflection\ClassMemberAccessAnswerer;
13: use PHPStan\Reflection\ExtendedMethodReflection;
14: use PHPStan\Reflection\ExtendedPropertyReflection;
15: use PHPStan\Reflection\InitializerExprTypeResolver;
16: use PHPStan\Reflection\TrivialParametersAcceptor;
17: use PHPStan\Reflection\Type\IntersectionTypeUnresolvedMethodPrototypeReflection;
18: use PHPStan\Reflection\Type\IntersectionTypeUnresolvedPropertyPrototypeReflection;
19: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
20: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
21: use PHPStan\ShouldNotHappenException;
22: use PHPStan\TrinaryLogic;
23: use PHPStan\Type\Accessory\AccessoryArrayListType;
24: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
25: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
26: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
27: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
28: use PHPStan\Type\Accessory\AccessoryNumericStringType;
29: use PHPStan\Type\Accessory\AccessoryType;
30: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
31: use PHPStan\Type\Accessory\NonEmptyArrayType;
32: use PHPStan\Type\Constant\ConstantArrayType;
33: use PHPStan\Type\Constant\ConstantIntegerType;
34: use PHPStan\Type\Constant\ConstantStringType;
35: use PHPStan\Type\Generic\TemplateType;
36: use PHPStan\Type\Generic\TemplateTypeMap;
37: use PHPStan\Type\Generic\TemplateTypeVariance;
38: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
39: use PHPStan\Type\Traits\NonRemoveableTypeTrait;
40: use function array_intersect_key;
41: use function array_map;
42: use function array_shift;
43: use function array_unique;
44: use function array_values;
45: use function count;
46: use function implode;
47: use function in_array;
48: use function ksort;
49: use function md5;
50: use function sprintf;
51: use function strcasecmp;
52: use function strlen;
53: use function substr;
54: use function usort;
55:
56: /** @api */
57: class IntersectionType implements CompoundType
58: {
59:
60: use NonRemoveableTypeTrait;
61: use NonGeneralizableTypeTrait;
62:
63: private bool $sortedTypes = false;
64:
65: /**
66: * @api
67: * @param Type[] $types
68: */
69: public function __construct(private array $types)
70: {
71: if (count($types) < 2) {
72: throw new ShouldNotHappenException(sprintf(
73: 'Cannot create %s with: %s',
74: self::class,
75: implode(', ', array_map(static fn (Type $type): string => $type->describe(VerbosityLevel::value()), $types)),
76: ));
77: }
78: }
79:
80: /**
81: * @return Type[]
82: */
83: public function getTypes(): array
84: {
85: return $this->types;
86: }
87:
88: /**
89: * @return Type[]
90: */
91: private function getSortedTypes(): array
92: {
93: if ($this->sortedTypes) {
94: return $this->types;
95: }
96:
97: $this->types = UnionTypeHelper::sortTypes($this->types);
98: $this->sortedTypes = true;
99:
100: return $this->types;
101: }
102:
103: public function inferTemplateTypesOn(Type $templateType): TemplateTypeMap
104: {
105: $types = TemplateTypeMap::createEmpty();
106:
107: foreach ($this->types as $type) {
108: $types = $types->intersect($templateType->inferTemplateTypes($type));
109: }
110:
111: return $types;
112: }
113:
114: public function getReferencedClasses(): array
115: {
116: $classes = [];
117: foreach ($this->types as $type) {
118: foreach ($type->getReferencedClasses() as $className) {
119: $classes[] = $className;
120: }
121: }
122:
123: return $classes;
124: }
125:
126: public function getObjectClassNames(): array
127: {
128: $objectClassNames = [];
129: foreach ($this->types as $type) {
130: $innerObjectClassNames = $type->getObjectClassNames();
131: foreach ($innerObjectClassNames as $innerObjectClassName) {
132: $objectClassNames[] = $innerObjectClassName;
133: }
134: }
135:
136: return array_values(array_unique($objectClassNames));
137: }
138:
139: public function getObjectClassReflections(): array
140: {
141: $reflections = [];
142: foreach ($this->types as $type) {
143: foreach ($type->getObjectClassReflections() as $reflection) {
144: $reflections[] = $reflection;
145: }
146: }
147:
148: return $reflections;
149: }
150:
151: public function getArrays(): array
152: {
153: $arrays = [];
154: foreach ($this->types as $type) {
155: foreach ($type->getArrays() as $array) {
156: $arrays[] = $array;
157: }
158: }
159:
160: return $arrays;
161: }
162:
163: public function getConstantArrays(): array
164: {
165: $constantArrays = [];
166: foreach ($this->types as $type) {
167: foreach ($type->getConstantArrays() as $constantArray) {
168: $constantArrays[] = $constantArray;
169: }
170: }
171:
172: return $constantArrays;
173: }
174:
175: public function getConstantStrings(): array
176: {
177: $strings = [];
178: foreach ($this->types as $type) {
179: foreach ($type->getConstantStrings() as $string) {
180: $strings[] = $string;
181: }
182: }
183:
184: return $strings;
185: }
186:
187: public function accepts(Type $otherType, bool $strictTypes): AcceptsResult
188: {
189: $result = AcceptsResult::createYes();
190: foreach ($this->types as $type) {
191: $result = $result->and($type->accepts($otherType, $strictTypes));
192: }
193:
194: if (!$result->yes()) {
195: $isList = $otherType->isList();
196: $reasons = $result->reasons;
197: $verbosity = VerbosityLevel::getRecommendedLevelByType($this, $otherType);
198: if ($this->isList()->yes() && !$isList->yes()) {
199: $reasons[] = sprintf(
200: '%s %s a list.',
201: $otherType->describe($verbosity),
202: $isList->no() ? 'is not' : 'might not be',
203: );
204: }
205:
206: $isNonEmpty = $otherType->isIterableAtLeastOnce();
207: if ($this->isIterableAtLeastOnce()->yes() && !$isNonEmpty->yes()) {
208: $reasons[] = sprintf(
209: '%s %s empty.',
210: $otherType->describe($verbosity),
211: $isNonEmpty->no() ? 'is' : 'might be',
212: );
213: }
214:
215: if (count($reasons) > 0) {
216: return new AcceptsResult($result->result, $reasons);
217: }
218: }
219:
220: return $result;
221: }
222:
223: public function isSuperTypeOf(Type $otherType): IsSuperTypeOfResult
224: {
225: if ($otherType instanceof IntersectionType && $this->equals($otherType)) {
226: return IsSuperTypeOfResult::createYes();
227: }
228:
229: if ($otherType instanceof NeverType) {
230: return IsSuperTypeOfResult::createYes();
231: }
232:
233: return IsSuperTypeOfResult::createYes()->and(...array_map(static fn (Type $innerType) => $innerType->isSuperTypeOf($otherType), $this->types));
234: }
235:
236: public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult
237: {
238: if (($otherType instanceof self || $otherType instanceof UnionType) && !$otherType instanceof TemplateType) {
239: return $otherType->isSuperTypeOf($this);
240: }
241:
242: $result = IsSuperTypeOfResult::maxMin(...array_map(static fn (Type $innerType) => $otherType->isSuperTypeOf($innerType), $this->types));
243: if ($this->isOversizedArray()->yes()) {
244: if (!$result->no()) {
245: return IsSuperTypeOfResult::createYes();
246: }
247: }
248:
249: return $result;
250: }
251:
252: public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult
253: {
254: $result = AcceptsResult::maxMin(...array_map(static fn (Type $innerType) => $acceptingType->accepts($innerType, $strictTypes), $this->types));
255: if ($this->isOversizedArray()->yes()) {
256: if (!$result->no()) {
257: return AcceptsResult::createYes();
258: }
259: }
260:
261: return $result;
262: }
263:
264: public function equals(Type $type): bool
265: {
266: if (!$type instanceof static) {
267: return false;
268: }
269:
270: if (count($this->types) !== count($type->types)) {
271: return false;
272: }
273:
274: $otherTypes = $type->types;
275: foreach ($this->types as $innerType) {
276: $match = false;
277: foreach ($otherTypes as $i => $otherType) {
278: if (!$innerType->equals($otherType)) {
279: continue;
280: }
281:
282: $match = true;
283: unset($otherTypes[$i]);
284: break;
285: }
286:
287: if (!$match) {
288: return false;
289: }
290: }
291:
292: return count($otherTypes) === 0;
293: }
294:
295: public function describe(VerbosityLevel $level): string
296: {
297: return $level->handle(
298: function () use ($level): string {
299: $typeNames = [];
300: $isList = $this->isList()->yes();
301: $valueType = null;
302: foreach ($this->getSortedTypes() as $type) {
303: if ($isList) {
304: if ($type instanceof ArrayType || $type instanceof ConstantArrayType) {
305: $valueType = $type->getIterableValueType();
306: continue;
307: }
308: if ($type instanceof NonEmptyArrayType) {
309: continue;
310: }
311: }
312: if ($type instanceof AccessoryType) {
313: continue;
314: }
315: $typeNames[] = $type->generalize(GeneralizePrecision::lessSpecific())->describe($level);
316: }
317:
318: if ($isList) {
319: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
320: $innerType = '';
321: if ($valueType !== null && !$isMixedValueType) {
322: $innerType = sprintf('<%s>', $valueType->describe($level));
323: }
324:
325: $typeNames[] = 'list' . $innerType;
326: }
327:
328: usort($typeNames, static function ($a, $b) {
329: $cmp = strcasecmp($a, $b);
330: if ($cmp !== 0) {
331: return $cmp;
332: }
333:
334: return $a <=> $b;
335: });
336:
337: return implode('&', $typeNames);
338: },
339: fn (): string => $this->describeItself($level, true),
340: fn (): string => $this->describeItself($level, false),
341: );
342: }
343:
344: private function describeItself(VerbosityLevel $level, bool $skipAccessoryTypes): string
345: {
346: $baseTypes = [];
347: $typesToDescribe = [];
348: $skipTypeNames = [];
349:
350: $nonEmptyStr = false;
351: $nonFalsyStr = false;
352: $isList = $this->isList()->yes();
353: $isArray = $this->isArray()->yes();
354: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
355: $describedTypes = [];
356: foreach ($this->getSortedTypes() as $i => $type) {
357: if ($type instanceof AccessoryNonEmptyStringType
358: || $type instanceof AccessoryLiteralStringType
359: || $type instanceof AccessoryNumericStringType
360: || $type instanceof AccessoryNonFalsyStringType
361: || $type instanceof AccessoryLowercaseStringType
362: || $type instanceof AccessoryUppercaseStringType
363: ) {
364: if (
365: ($type instanceof AccessoryLowercaseStringType || $type instanceof AccessoryUppercaseStringType)
366: && !$level->isPrecise()
367: ) {
368: continue;
369: }
370: if ($type instanceof AccessoryNonFalsyStringType) {
371: $nonFalsyStr = true;
372: }
373: if ($type instanceof AccessoryNonEmptyStringType) {
374: $nonEmptyStr = true;
375: }
376: if ($nonEmptyStr && $nonFalsyStr) {
377: // prevent redundant 'non-empty-string&non-falsy-string'
378: foreach ($typesToDescribe as $key => $typeToDescribe) {
379: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
380: continue;
381: }
382:
383: unset($typesToDescribe[$key]);
384: }
385: }
386:
387: $typesToDescribe[$i] = $type;
388: $skipTypeNames[] = 'string';
389: continue;
390: }
391: if ($isList || $isArray) {
392: if ($type instanceof ArrayType) {
393: $keyType = $type->getKeyType();
394: $valueType = $type->getItemType();
395: if ($isList) {
396: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
397: $valueTypeDescription = '';
398: if (!$isMixedValueType) {
399: $valueTypeDescription = sprintf('<%s>', $valueType->describe($level));
400: }
401:
402: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-list' : 'list') . $valueTypeDescription;
403: } else {
404: $isMixedKeyType = $keyType instanceof MixedType && $keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$keyType->isExplicitMixed();
405: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
406: $typeDescription = '';
407: if (!$isMixedKeyType) {
408: $typeDescription = sprintf('<%s, %s>', $keyType->describe($level), $valueType->describe($level));
409: } elseif (!$isMixedValueType) {
410: $typeDescription = sprintf('<%s>', $valueType->describe($level));
411: }
412:
413: $describedTypes[$i] = ($isNonEmptyArray ? 'non-empty-array' : 'array') . $typeDescription;
414: }
415: continue;
416: } elseif ($type instanceof ConstantArrayType) {
417: $description = $type->describe($level);
418: $descriptionWithoutKind = substr($description, strlen('array'));
419: $begin = $isList ? 'list' : 'array';
420: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
421: $begin = 'non-empty-' . $begin;
422: }
423:
424: $describedTypes[$i] = $begin . $descriptionWithoutKind;
425: continue;
426: }
427: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
428: continue;
429: }
430: }
431:
432: if ($type instanceof CallableType && $type->isCommonCallable()) {
433: $typesToDescribe[$i] = $type;
434: $skipTypeNames[] = 'object';
435: $skipTypeNames[] = 'string';
436: continue;
437: }
438:
439: if (!$type instanceof AccessoryType) {
440: $baseTypes[$i] = $type;
441: continue;
442: }
443:
444: if ($skipAccessoryTypes) {
445: continue;
446: }
447:
448: $typesToDescribe[$i] = $type;
449: }
450:
451: foreach ($baseTypes as $i => $type) {
452: $typeDescription = $type->describe($level);
453:
454: if (in_array($typeDescription, ['object', 'string'], true) && in_array($typeDescription, $skipTypeNames, true)) {
455: foreach ($typesToDescribe as $j => $typeToDescribe) {
456: if ($typeToDescribe instanceof CallableType && $typeToDescribe->isCommonCallable()) {
457: $describedTypes[$i] = 'callable-' . $typeDescription;
458: unset($typesToDescribe[$j]);
459: continue 2;
460: }
461: }
462: }
463:
464: if (in_array($typeDescription, $skipTypeNames, true)) {
465: continue;
466: }
467:
468: $describedTypes[$i] = $type->describe($level);
469: }
470:
471: foreach ($typesToDescribe as $i => $typeToDescribe) {
472: $describedTypes[$i] = $typeToDescribe->describe($level);
473: }
474:
475: ksort($describedTypes);
476:
477: return implode('&', $describedTypes);
478: }
479:
480: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
481: {
482: return $this->intersectTypes(static fn (Type $type): Type => $type->getTemplateType($ancestorClassName, $templateTypeName));
483: }
484:
485: public function isObject(): TrinaryLogic
486: {
487: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isObject());
488: }
489:
490: public function isEnum(): TrinaryLogic
491: {
492: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isEnum());
493: }
494:
495: public function canAccessProperties(): TrinaryLogic
496: {
497: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessProperties());
498: }
499:
500: public function hasProperty(string $propertyName): TrinaryLogic
501: {
502: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasProperty($propertyName));
503: }
504:
505: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
506: {
507: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
508: }
509:
510: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
511: {
512: $propertyPrototypes = [];
513: foreach ($this->types as $type) {
514: if (!$type->hasProperty($propertyName)->yes()) {
515: continue;
516: }
517:
518: $propertyPrototypes[] = $type->getUnresolvedPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
519: }
520:
521: $propertiesCount = count($propertyPrototypes);
522: if ($propertiesCount === 0) {
523: throw new ShouldNotHappenException();
524: }
525:
526: if ($propertiesCount === 1) {
527: return $propertyPrototypes[0];
528: }
529:
530: return new IntersectionTypeUnresolvedPropertyPrototypeReflection($propertyName, $propertyPrototypes);
531: }
532:
533: public function canCallMethods(): TrinaryLogic
534: {
535: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canCallMethods());
536: }
537:
538: public function hasMethod(string $methodName): TrinaryLogic
539: {
540: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasMethod($methodName));
541: }
542:
543: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
544: {
545: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
546: }
547:
548: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
549: {
550: $methodPrototypes = [];
551: foreach ($this->types as $type) {
552: if (!$type->hasMethod($methodName)->yes()) {
553: continue;
554: }
555:
556: $methodPrototypes[] = $type->getUnresolvedMethodPrototype($methodName, $scope)->withCalledOnType($this);
557: }
558:
559: $methodsCount = count($methodPrototypes);
560: if ($methodsCount === 0) {
561: throw new ShouldNotHappenException();
562: }
563:
564: if ($methodsCount === 1) {
565: return $methodPrototypes[0];
566: }
567:
568: return new IntersectionTypeUnresolvedMethodPrototypeReflection($methodName, $methodPrototypes);
569: }
570:
571: public function canAccessConstants(): TrinaryLogic
572: {
573: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->canAccessConstants());
574: }
575:
576: public function hasConstant(string $constantName): TrinaryLogic
577: {
578: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasConstant($constantName));
579: }
580:
581: public function getConstant(string $constantName): ClassConstantReflection
582: {
583: foreach ($this->types as $type) {
584: if ($type->hasConstant($constantName)->yes()) {
585: return $type->getConstant($constantName);
586: }
587: }
588:
589: throw new ShouldNotHappenException();
590: }
591:
592: public function isIterable(): TrinaryLogic
593: {
594: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isIterable());
595: }
596:
597: public function isIterableAtLeastOnce(): TrinaryLogic
598: {
599: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isIterableAtLeastOnce());
600: }
601:
602: public function getArraySize(): Type
603: {
604: return $this->intersectTypes(static fn (Type $type): Type => $type->getArraySize());
605: }
606:
607: public function getIterableKeyType(): Type
608: {
609: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType());
610: }
611:
612: public function getFirstIterableKeyType(): Type
613: {
614: return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableKeyType());
615: }
616:
617: public function getLastIterableKeyType(): Type
618: {
619: return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableKeyType());
620: }
621:
622: public function getIterableValueType(): Type
623: {
624: return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType());
625: }
626:
627: public function getFirstIterableValueType(): Type
628: {
629: return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableValueType());
630: }
631:
632: public function getLastIterableValueType(): Type
633: {
634: return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableValueType());
635: }
636:
637: public function isArray(): TrinaryLogic
638: {
639: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isArray());
640: }
641:
642: public function isConstantArray(): TrinaryLogic
643: {
644: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantArray());
645: }
646:
647: public function isOversizedArray(): TrinaryLogic
648: {
649: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOversizedArray());
650: }
651:
652: public function isList(): TrinaryLogic
653: {
654: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isList());
655: }
656:
657: public function isString(): TrinaryLogic
658: {
659: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isString());
660: }
661:
662: public function isNumericString(): TrinaryLogic
663: {
664: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNumericString());
665: }
666:
667: public function isNonEmptyString(): TrinaryLogic
668: {
669: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonEmptyString());
670: }
671:
672: public function isNonFalsyString(): TrinaryLogic
673: {
674: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNonFalsyString());
675: }
676:
677: public function isLiteralString(): TrinaryLogic
678: {
679: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLiteralString());
680: }
681:
682: public function isLowercaseString(): TrinaryLogic
683: {
684: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isLowercaseString());
685: }
686:
687: public function isUppercaseString(): TrinaryLogic
688: {
689: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isUppercaseString());
690: }
691:
692: public function isClassString(): TrinaryLogic
693: {
694: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isClassString());
695: }
696:
697: public function getClassStringObjectType(): Type
698: {
699: return $this->intersectTypes(static fn (Type $type): Type => $type->getClassStringObjectType());
700: }
701:
702: public function getObjectTypeOrClassStringObjectType(): Type
703: {
704: return $this->intersectTypes(static fn (Type $type): Type => $type->getObjectTypeOrClassStringObjectType());
705: }
706:
707: public function isVoid(): TrinaryLogic
708: {
709: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isVoid());
710: }
711:
712: public function isScalar(): TrinaryLogic
713: {
714: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isScalar());
715: }
716:
717: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
718: {
719: return new BooleanType();
720: }
721:
722: public function isOffsetAccessible(): TrinaryLogic
723: {
724: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessible());
725: }
726:
727: public function isOffsetAccessLegal(): TrinaryLogic
728: {
729: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessLegal());
730: }
731:
732: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
733: {
734: if ($this->isList()->yes() && $this->isIterableAtLeastOnce()->yes()) {
735: $arrayKeyOffsetType = $offsetType->toArrayKey();
736: if ((new ConstantIntegerType(0))->isSuperTypeOf($arrayKeyOffsetType)->yes()) {
737: return TrinaryLogic::createYes();
738: }
739: }
740:
741: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->hasOffsetValueType($offsetType));
742: }
743:
744: public function getOffsetValueType(Type $offsetType): Type
745: {
746: $result = $this->intersectTypes(static fn (Type $type): Type => $type->getOffsetValueType($offsetType));
747: if ($this->isOversizedArray()->yes()) {
748: return TypeUtils::toBenevolentUnion($result);
749: }
750:
751: return $result;
752: }
753:
754: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
755: {
756: if ($this->isOversizedArray()->yes()) {
757: return $this->intersectTypes(static function (Type $type) use ($offsetType, $valueType, $unionValues): Type {
758: // avoid new HasOffsetValueType being intersected with oversized array
759: if (!$type instanceof ArrayType) {
760: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
761: }
762:
763: if (!$offsetType instanceof ConstantStringType && !$offsetType instanceof ConstantIntegerType) {
764: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
765: }
766:
767: if (!$offsetType->isSuperTypeOf($type->getKeyType())->yes()) {
768: return $type->setOffsetValueType($offsetType, $valueType, $unionValues);
769: }
770:
771: return TypeCombinator::intersect(
772: new ArrayType(
773: TypeCombinator::union($type->getKeyType(), $offsetType),
774: TypeCombinator::union($type->getItemType(), $valueType),
775: ),
776: new NonEmptyArrayType(),
777: );
778: });
779: }
780: return $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType, $unionValues));
781: }
782:
783: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
784: {
785: return $this->intersectTypes(static fn (Type $type): Type => $type->setExistingOffsetValueType($offsetType, $valueType));
786: }
787:
788: public function unsetOffset(Type $offsetType): Type
789: {
790: return $this->intersectTypes(static fn (Type $type): Type => $type->unsetOffset($offsetType));
791: }
792:
793: public function getKeysArray(): Type
794: {
795: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArray());
796: }
797:
798: public function getValuesArray(): Type
799: {
800: return $this->intersectTypes(static fn (Type $type): Type => $type->getValuesArray());
801: }
802:
803: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
804: {
805: return $this->intersectTypes(static fn (Type $type): Type => $type->chunkArray($lengthType, $preserveKeys));
806: }
807:
808: public function fillKeysArray(Type $valueType): Type
809: {
810: return $this->intersectTypes(static fn (Type $type): Type => $type->fillKeysArray($valueType));
811: }
812:
813: public function flipArray(): Type
814: {
815: return $this->intersectTypes(static fn (Type $type): Type => $type->flipArray());
816: }
817:
818: public function intersectKeyArray(Type $otherArraysType): Type
819: {
820: return $this->intersectTypes(static fn (Type $type): Type => $type->intersectKeyArray($otherArraysType));
821: }
822:
823: public function popArray(): Type
824: {
825: return $this->intersectTypes(static fn (Type $type): Type => $type->popArray());
826: }
827:
828: public function reverseArray(TrinaryLogic $preserveKeys): Type
829: {
830: return $this->intersectTypes(static fn (Type $type): Type => $type->reverseArray($preserveKeys));
831: }
832:
833: public function searchArray(Type $needleType): Type
834: {
835: return $this->intersectTypes(static fn (Type $type): Type => $type->searchArray($needleType));
836: }
837:
838: public function shiftArray(): Type
839: {
840: return $this->intersectTypes(static fn (Type $type): Type => $type->shiftArray());
841: }
842:
843: public function shuffleArray(): Type
844: {
845: return $this->intersectTypes(static fn (Type $type): Type => $type->shuffleArray());
846: }
847:
848: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
849: {
850: return $this->intersectTypes(static fn (Type $type): Type => $type->sliceArray($offsetType, $lengthType, $preserveKeys));
851: }
852:
853: public function getEnumCases(): array
854: {
855: $compare = [];
856: foreach ($this->types as $type) {
857: $oneType = [];
858: foreach ($type->getEnumCases() as $enumCase) {
859: $oneType[md5($enumCase->describe(VerbosityLevel::typeOnly()))] = $enumCase;
860: }
861: $compare[] = $oneType;
862: }
863:
864: return array_values(array_intersect_key(...$compare));
865: }
866:
867: public function isCallable(): TrinaryLogic
868: {
869: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCallable());
870: }
871:
872: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
873: {
874: if ($this->isCallable()->no()) {
875: throw new ShouldNotHappenException();
876: }
877:
878: return [new TrivialParametersAcceptor()];
879: }
880:
881: public function isCloneable(): TrinaryLogic
882: {
883: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCloneable());
884: }
885:
886: public function isSmallerThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
887: {
888: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThan($otherType, $phpVersion));
889: }
890:
891: public function isSmallerThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
892: {
893: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThanOrEqual($otherType, $phpVersion));
894: }
895:
896: public function isNull(): TrinaryLogic
897: {
898: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNull());
899: }
900:
901: public function isConstantValue(): TrinaryLogic
902: {
903: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantValue());
904: }
905:
906: public function isConstantScalarValue(): TrinaryLogic
907: {
908: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantScalarValue());
909: }
910:
911: public function getConstantScalarTypes(): array
912: {
913: $scalarTypes = [];
914: foreach ($this->types as $type) {
915: foreach ($type->getConstantScalarTypes() as $scalarType) {
916: $scalarTypes[] = $scalarType;
917: }
918: }
919:
920: return $scalarTypes;
921: }
922:
923: public function getConstantScalarValues(): array
924: {
925: $values = [];
926: foreach ($this->types as $type) {
927: foreach ($type->getConstantScalarValues() as $value) {
928: $values[] = $value;
929: }
930: }
931:
932: return $values;
933: }
934:
935: public function isTrue(): TrinaryLogic
936: {
937: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isTrue());
938: }
939:
940: public function isFalse(): TrinaryLogic
941: {
942: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFalse());
943: }
944:
945: public function isBoolean(): TrinaryLogic
946: {
947: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isBoolean());
948: }
949:
950: public function isFloat(): TrinaryLogic
951: {
952: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFloat());
953: }
954:
955: public function isInteger(): TrinaryLogic
956: {
957: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isInteger());
958: }
959:
960: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
961: {
962: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThan($type, $phpVersion));
963: }
964:
965: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
966: {
967: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThanOrEqual($type, $phpVersion));
968: }
969:
970: public function getSmallerType(PhpVersion $phpVersion): Type
971: {
972: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerType($phpVersion));
973: }
974:
975: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
976: {
977: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerOrEqualType($phpVersion));
978: }
979:
980: public function getGreaterType(PhpVersion $phpVersion): Type
981: {
982: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterType($phpVersion));
983: }
984:
985: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
986: {
987: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterOrEqualType($phpVersion));
988: }
989:
990: public function toBoolean(): BooleanType
991: {
992: $type = $this->intersectTypes(static fn (Type $type): BooleanType => $type->toBoolean());
993:
994: if (!$type instanceof BooleanType) {
995: return new BooleanType();
996: }
997:
998: return $type;
999: }
1000:
1001: public function toNumber(): Type
1002: {
1003: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toNumber());
1004:
1005: return $type;
1006: }
1007:
1008: public function toAbsoluteNumber(): Type
1009: {
1010: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toAbsoluteNumber());
1011:
1012: return $type;
1013: }
1014:
1015: public function toString(): Type
1016: {
1017: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toString());
1018:
1019: return $type;
1020: }
1021:
1022: public function toInteger(): Type
1023: {
1024: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toInteger());
1025:
1026: return $type;
1027: }
1028:
1029: public function toFloat(): Type
1030: {
1031: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toFloat());
1032:
1033: return $type;
1034: }
1035:
1036: public function toArray(): Type
1037: {
1038: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toArray());
1039:
1040: return $type;
1041: }
1042:
1043: public function toArrayKey(): Type
1044: {
1045: if ($this->isNumericString()->yes()) {
1046: return new IntegerType();
1047: }
1048:
1049: if ($this->isString()->yes()) {
1050: return $this;
1051: }
1052:
1053: return $this->intersectTypes(static fn (Type $type): Type => $type->toArrayKey());
1054: }
1055:
1056: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1057: {
1058: $types = TemplateTypeMap::createEmpty();
1059:
1060: foreach ($this->types as $type) {
1061: $types = $types->intersect($type->inferTemplateTypes($receivedType));
1062: }
1063:
1064: return $types;
1065: }
1066:
1067: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1068: {
1069: $references = [];
1070:
1071: foreach ($this->types as $type) {
1072: foreach ($type->getReferencedTemplateTypes($positionVariance) as $reference) {
1073: $references[] = $reference;
1074: }
1075: }
1076:
1077: return $references;
1078: }
1079:
1080: public function traverse(callable $cb): Type
1081: {
1082: $types = [];
1083: $changed = false;
1084:
1085: foreach ($this->types as $type) {
1086: $newType = $cb($type);
1087: if ($type !== $newType) {
1088: $changed = true;
1089: }
1090: $types[] = $newType;
1091: }
1092:
1093: if ($changed) {
1094: return TypeCombinator::intersect(...$types);
1095: }
1096:
1097: return $this;
1098: }
1099:
1100: public function traverseSimultaneously(Type $right, callable $cb): Type
1101: {
1102: $types = [];
1103: $changed = false;
1104:
1105: if (!$right instanceof self) {
1106: return $this;
1107: }
1108:
1109: if (count($this->getTypes()) !== count($right->getTypes())) {
1110: return $this;
1111: }
1112:
1113: foreach ($this->getSortedTypes() as $i => $leftType) {
1114: $rightType = $right->getSortedTypes()[$i];
1115: $newType = $cb($leftType, $rightType);
1116: if ($leftType !== $newType) {
1117: $changed = true;
1118: }
1119: $types[] = $newType;
1120: }
1121:
1122: if ($changed) {
1123: return TypeCombinator::intersect(...$types);
1124: }
1125:
1126: return $this;
1127: }
1128:
1129: public function tryRemove(Type $typeToRemove): ?Type
1130: {
1131: return $this->intersectTypes(static fn (Type $type): Type => TypeCombinator::remove($type, $typeToRemove));
1132: }
1133:
1134: public function exponentiate(Type $exponent): Type
1135: {
1136: return $this->intersectTypes(static fn (Type $type): Type => $type->exponentiate($exponent));
1137: }
1138:
1139: public function getFiniteTypes(): array
1140: {
1141: $compare = [];
1142: foreach ($this->types as $type) {
1143: $oneType = [];
1144: foreach ($type->getFiniteTypes() as $finiteType) {
1145: $oneType[md5($finiteType->describe(VerbosityLevel::typeOnly()))] = $finiteType;
1146: }
1147: $compare[] = $oneType;
1148: }
1149:
1150: $result = array_values(array_intersect_key(...$compare));
1151:
1152: if (count($result) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1153: return [];
1154: }
1155:
1156: return $result;
1157: }
1158:
1159: /**
1160: * @param callable(Type $type): TrinaryLogic $getResult
1161: */
1162: private function intersectResults(callable $getResult): TrinaryLogic
1163: {
1164: return TrinaryLogic::lazyMaxMin($this->types, $getResult);
1165: }
1166:
1167: /**
1168: * @param callable(Type $type): Type $getType
1169: */
1170: private function intersectTypes(callable $getType): Type
1171: {
1172: $operands = array_map($getType, $this->types);
1173: return TypeCombinator::intersect(...$operands);
1174: }
1175:
1176: public function toPhpDocNode(): TypeNode
1177: {
1178: $baseTypes = [];
1179: $typesToDescribe = [];
1180: $skipTypeNames = [];
1181:
1182: $nonEmptyStr = false;
1183: $nonFalsyStr = false;
1184: $isList = $this->isList()->yes();
1185: $isArray = $this->isArray()->yes();
1186: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
1187: $describedTypes = [];
1188:
1189: foreach ($this->getSortedTypes() as $i => $type) {
1190: if ($type instanceof AccessoryNonEmptyStringType
1191: || $type instanceof AccessoryLiteralStringType
1192: || $type instanceof AccessoryNumericStringType
1193: || $type instanceof AccessoryNonFalsyStringType
1194: || $type instanceof AccessoryLowercaseStringType
1195: || $type instanceof AccessoryUppercaseStringType
1196: ) {
1197: if ($type instanceof AccessoryNonFalsyStringType) {
1198: $nonFalsyStr = true;
1199: }
1200: if ($type instanceof AccessoryNonEmptyStringType) {
1201: $nonEmptyStr = true;
1202: }
1203: if ($nonEmptyStr && $nonFalsyStr) {
1204: // prevent redundant 'non-empty-string&non-falsy-string'
1205: foreach ($typesToDescribe as $key => $typeToDescribe) {
1206: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
1207: continue;
1208: }
1209:
1210: unset($typesToDescribe[$key]);
1211: }
1212: }
1213:
1214: $typesToDescribe[$i] = $type;
1215: $skipTypeNames[] = 'string';
1216: continue;
1217: }
1218:
1219: if ($isList || $isArray) {
1220: if ($type instanceof ArrayType) {
1221: $keyType = $type->getKeyType();
1222: $valueType = $type->getItemType();
1223: if ($isList) {
1224: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
1225: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-list' : 'list');
1226: if (!$isMixedValueType) {
1227: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1228: $valueType->toPhpDocNode(),
1229: ]);
1230: } else {
1231: $describedTypes[$i] = $identifierTypeNode;
1232: }
1233: } else {
1234: $isMixedKeyType = $keyType instanceof MixedType && $keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$keyType->isExplicitMixed();
1235: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
1236: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-array' : 'array');
1237: if (!$isMixedKeyType) {
1238: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1239: $keyType->toPhpDocNode(),
1240: $valueType->toPhpDocNode(),
1241: ]);
1242: } elseif (!$isMixedValueType) {
1243: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1244: $valueType->toPhpDocNode(),
1245: ]);
1246: } else {
1247: $describedTypes[$i] = $identifierTypeNode;
1248: }
1249: }
1250: continue;
1251: } elseif ($type instanceof ConstantArrayType) {
1252: $constantArrayTypeNode = $type->toPhpDocNode();
1253: if ($constantArrayTypeNode instanceof ArrayShapeNode) {
1254: $newKind = $constantArrayTypeNode->kind;
1255: if ($isList) {
1256: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
1257: $newKind = ArrayShapeNode::KIND_NON_EMPTY_LIST;
1258: } else {
1259: $newKind = ArrayShapeNode::KIND_LIST;
1260: }
1261: } elseif ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
1262: $newKind = ArrayShapeNode::KIND_NON_EMPTY_ARRAY;
1263: }
1264:
1265: if ($newKind !== $constantArrayTypeNode->kind) {
1266: if ($constantArrayTypeNode->sealed) {
1267: $constantArrayTypeNode = ArrayShapeNode::createSealed($constantArrayTypeNode->items, $newKind);
1268: } else {
1269: $constantArrayTypeNode = ArrayShapeNode::createUnsealed($constantArrayTypeNode->items, $constantArrayTypeNode->unsealedType, $newKind);
1270: }
1271: }
1272:
1273: $describedTypes[$i] = $constantArrayTypeNode;
1274: continue;
1275: }
1276: }
1277: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
1278: continue;
1279: }
1280: }
1281:
1282: if (!$type instanceof AccessoryType) {
1283: $baseTypes[$i] = $type;
1284: continue;
1285: }
1286:
1287: $accessoryPhpDocNode = $type->toPhpDocNode();
1288: if ($accessoryPhpDocNode instanceof IdentifierTypeNode && $accessoryPhpDocNode->name === '') {
1289: continue;
1290: }
1291:
1292: $typesToDescribe[$i] = $type;
1293: }
1294:
1295: foreach ($baseTypes as $i => $type) {
1296: $typeNode = $type->toPhpDocNode();
1297: if ($typeNode instanceof GenericTypeNode && $typeNode->type->name === 'array') {
1298: $nonEmpty = false;
1299: $typeName = 'array';
1300: foreach ($typesToDescribe as $j => $typeToDescribe) {
1301: if ($typeToDescribe instanceof AccessoryArrayListType) {
1302: $typeName = 'list';
1303: if (count($typeNode->genericTypes) > 1) {
1304: array_shift($typeNode->genericTypes);
1305: }
1306: } elseif ($typeToDescribe instanceof NonEmptyArrayType) {
1307: $nonEmpty = true;
1308: } else {
1309: continue;
1310: }
1311:
1312: unset($typesToDescribe[$j]);
1313: }
1314:
1315: if ($nonEmpty) {
1316: $typeName = 'non-empty-' . $typeName;
1317: }
1318:
1319: $describedTypes[$i] = new GenericTypeNode(
1320: new IdentifierTypeNode($typeName),
1321: $typeNode->genericTypes,
1322: );
1323: continue;
1324: }
1325:
1326: if ($typeNode instanceof IdentifierTypeNode && in_array($typeNode->name, $skipTypeNames, true)) {
1327: continue;
1328: }
1329:
1330: $describedTypes[$i] = $typeNode;
1331: }
1332:
1333: foreach ($typesToDescribe as $i => $typeToDescribe) {
1334: $describedTypes[$i] = $typeToDescribe->toPhpDocNode();
1335: }
1336:
1337: ksort($describedTypes);
1338:
1339: $describedTypes = array_values($describedTypes);
1340:
1341: if (count($describedTypes) === 1) {
1342: return $describedTypes[0];
1343: }
1344:
1345: return new IntersectionTypeNode($describedTypes);
1346: }
1347:
1348: }
1349: