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:
781: $result = $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType, $unionValues));
782:
783: if ($offsetType !== null && $this->isList()->yes() && $this->isIterableAtLeastOnce()->yes() && (new ConstantIntegerType(1))->isSuperTypeOf($offsetType)->yes()) {
784: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
785: }
786:
787: return $result;
788: }
789:
790: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
791: {
792: return $this->intersectTypes(static fn (Type $type): Type => $type->setExistingOffsetValueType($offsetType, $valueType));
793: }
794:
795: public function unsetOffset(Type $offsetType): Type
796: {
797: return $this->intersectTypes(static fn (Type $type): Type => $type->unsetOffset($offsetType));
798: }
799:
800: public function getKeysArray(): Type
801: {
802: return $this->intersectTypes(static fn (Type $type): Type => $type->getKeysArray());
803: }
804:
805: public function getValuesArray(): Type
806: {
807: return $this->intersectTypes(static fn (Type $type): Type => $type->getValuesArray());
808: }
809:
810: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
811: {
812: return $this->intersectTypes(static fn (Type $type): Type => $type->chunkArray($lengthType, $preserveKeys));
813: }
814:
815: public function fillKeysArray(Type $valueType): Type
816: {
817: return $this->intersectTypes(static fn (Type $type): Type => $type->fillKeysArray($valueType));
818: }
819:
820: public function flipArray(): Type
821: {
822: return $this->intersectTypes(static fn (Type $type): Type => $type->flipArray());
823: }
824:
825: public function intersectKeyArray(Type $otherArraysType): Type
826: {
827: return $this->intersectTypes(static fn (Type $type): Type => $type->intersectKeyArray($otherArraysType));
828: }
829:
830: public function popArray(): Type
831: {
832: return $this->intersectTypes(static fn (Type $type): Type => $type->popArray());
833: }
834:
835: public function reverseArray(TrinaryLogic $preserveKeys): Type
836: {
837: return $this->intersectTypes(static fn (Type $type): Type => $type->reverseArray($preserveKeys));
838: }
839:
840: public function searchArray(Type $needleType): Type
841: {
842: return $this->intersectTypes(static fn (Type $type): Type => $type->searchArray($needleType));
843: }
844:
845: public function shiftArray(): Type
846: {
847: return $this->intersectTypes(static fn (Type $type): Type => $type->shiftArray());
848: }
849:
850: public function shuffleArray(): Type
851: {
852: return $this->intersectTypes(static fn (Type $type): Type => $type->shuffleArray());
853: }
854:
855: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
856: {
857: return $this->intersectTypes(static fn (Type $type): Type => $type->sliceArray($offsetType, $lengthType, $preserveKeys));
858: }
859:
860: public function getEnumCases(): array
861: {
862: $compare = [];
863: foreach ($this->types as $type) {
864: $oneType = [];
865: foreach ($type->getEnumCases() as $enumCase) {
866: $oneType[$enumCase->getClassName() . '::' . $enumCase->getEnumCaseName()] = $enumCase;
867: }
868: $compare[] = $oneType;
869: }
870:
871: return array_values(array_intersect_key(...$compare));
872: }
873:
874: public function isCallable(): TrinaryLogic
875: {
876: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCallable());
877: }
878:
879: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
880: {
881: if ($this->isCallable()->no()) {
882: throw new ShouldNotHappenException();
883: }
884:
885: return [new TrivialParametersAcceptor()];
886: }
887:
888: public function isCloneable(): TrinaryLogic
889: {
890: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isCloneable());
891: }
892:
893: public function isSmallerThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
894: {
895: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThan($otherType, $phpVersion));
896: }
897:
898: public function isSmallerThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
899: {
900: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThanOrEqual($otherType, $phpVersion));
901: }
902:
903: public function isNull(): TrinaryLogic
904: {
905: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isNull());
906: }
907:
908: public function isConstantValue(): TrinaryLogic
909: {
910: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantValue());
911: }
912:
913: public function isConstantScalarValue(): TrinaryLogic
914: {
915: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isConstantScalarValue());
916: }
917:
918: public function getConstantScalarTypes(): array
919: {
920: $scalarTypes = [];
921: foreach ($this->types as $type) {
922: foreach ($type->getConstantScalarTypes() as $scalarType) {
923: $scalarTypes[] = $scalarType;
924: }
925: }
926:
927: return $scalarTypes;
928: }
929:
930: public function getConstantScalarValues(): array
931: {
932: $values = [];
933: foreach ($this->types as $type) {
934: foreach ($type->getConstantScalarValues() as $value) {
935: $values[] = $value;
936: }
937: }
938:
939: return $values;
940: }
941:
942: public function isTrue(): TrinaryLogic
943: {
944: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isTrue());
945: }
946:
947: public function isFalse(): TrinaryLogic
948: {
949: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFalse());
950: }
951:
952: public function isBoolean(): TrinaryLogic
953: {
954: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isBoolean());
955: }
956:
957: public function isFloat(): TrinaryLogic
958: {
959: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isFloat());
960: }
961:
962: public function isInteger(): TrinaryLogic
963: {
964: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $type->isInteger());
965: }
966:
967: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
968: {
969: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThan($type, $phpVersion));
970: }
971:
972: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
973: {
974: return $this->intersectResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThanOrEqual($type, $phpVersion));
975: }
976:
977: public function getSmallerType(PhpVersion $phpVersion): Type
978: {
979: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerType($phpVersion));
980: }
981:
982: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
983: {
984: return $this->intersectTypes(static fn (Type $type): Type => $type->getSmallerOrEqualType($phpVersion));
985: }
986:
987: public function getGreaterType(PhpVersion $phpVersion): Type
988: {
989: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterType($phpVersion));
990: }
991:
992: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
993: {
994: return $this->intersectTypes(static fn (Type $type): Type => $type->getGreaterOrEqualType($phpVersion));
995: }
996:
997: public function toBoolean(): BooleanType
998: {
999: $type = $this->intersectTypes(static fn (Type $type): BooleanType => $type->toBoolean());
1000:
1001: if (!$type instanceof BooleanType) {
1002: return new BooleanType();
1003: }
1004:
1005: return $type;
1006: }
1007:
1008: public function toNumber(): Type
1009: {
1010: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toNumber());
1011:
1012: return $type;
1013: }
1014:
1015: public function toAbsoluteNumber(): Type
1016: {
1017: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toAbsoluteNumber());
1018:
1019: return $type;
1020: }
1021:
1022: public function toString(): Type
1023: {
1024: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toString());
1025:
1026: return $type;
1027: }
1028:
1029: public function toInteger(): Type
1030: {
1031: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toInteger());
1032:
1033: return $type;
1034: }
1035:
1036: public function toFloat(): Type
1037: {
1038: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toFloat());
1039:
1040: return $type;
1041: }
1042:
1043: public function toArray(): Type
1044: {
1045: $type = $this->intersectTypes(static fn (Type $type): Type => $type->toArray());
1046:
1047: return $type;
1048: }
1049:
1050: public function toArrayKey(): Type
1051: {
1052: if ($this->isNumericString()->yes()) {
1053: return new IntegerType();
1054: }
1055:
1056: if ($this->isString()->yes()) {
1057: return $this;
1058: }
1059:
1060: return $this->intersectTypes(static fn (Type $type): Type => $type->toArrayKey());
1061: }
1062:
1063: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1064: {
1065: $types = TemplateTypeMap::createEmpty();
1066:
1067: foreach ($this->types as $type) {
1068: $types = $types->intersect($type->inferTemplateTypes($receivedType));
1069: }
1070:
1071: return $types;
1072: }
1073:
1074: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1075: {
1076: $references = [];
1077:
1078: foreach ($this->types as $type) {
1079: foreach ($type->getReferencedTemplateTypes($positionVariance) as $reference) {
1080: $references[] = $reference;
1081: }
1082: }
1083:
1084: return $references;
1085: }
1086:
1087: public function traverse(callable $cb): Type
1088: {
1089: $types = [];
1090: $changed = false;
1091:
1092: foreach ($this->types as $type) {
1093: $newType = $cb($type);
1094: if ($type !== $newType) {
1095: $changed = true;
1096: }
1097: $types[] = $newType;
1098: }
1099:
1100: if ($changed) {
1101: return TypeCombinator::intersect(...$types);
1102: }
1103:
1104: return $this;
1105: }
1106:
1107: public function traverseSimultaneously(Type $right, callable $cb): Type
1108: {
1109: $types = [];
1110: $changed = false;
1111:
1112: if (!$right instanceof self) {
1113: return $this;
1114: }
1115:
1116: if (count($this->getTypes()) !== count($right->getTypes())) {
1117: return $this;
1118: }
1119:
1120: foreach ($this->getSortedTypes() as $i => $leftType) {
1121: $rightType = $right->getSortedTypes()[$i];
1122: $newType = $cb($leftType, $rightType);
1123: if ($leftType !== $newType) {
1124: $changed = true;
1125: }
1126: $types[] = $newType;
1127: }
1128:
1129: if ($changed) {
1130: return TypeCombinator::intersect(...$types);
1131: }
1132:
1133: return $this;
1134: }
1135:
1136: public function tryRemove(Type $typeToRemove): ?Type
1137: {
1138: return $this->intersectTypes(static fn (Type $type): Type => TypeCombinator::remove($type, $typeToRemove));
1139: }
1140:
1141: public function exponentiate(Type $exponent): Type
1142: {
1143: return $this->intersectTypes(static fn (Type $type): Type => $type->exponentiate($exponent));
1144: }
1145:
1146: public function getFiniteTypes(): array
1147: {
1148: $compare = [];
1149: foreach ($this->types as $type) {
1150: $oneType = [];
1151: foreach ($type->getFiniteTypes() as $finiteType) {
1152: $oneType[md5($finiteType->describe(VerbosityLevel::typeOnly()))] = $finiteType;
1153: }
1154: $compare[] = $oneType;
1155: }
1156:
1157: $result = array_values(array_intersect_key(...$compare));
1158:
1159: if (count($result) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1160: return [];
1161: }
1162:
1163: return $result;
1164: }
1165:
1166: /**
1167: * @param callable(Type $type): TrinaryLogic $getResult
1168: */
1169: private function intersectResults(callable $getResult): TrinaryLogic
1170: {
1171: return TrinaryLogic::lazyMaxMin($this->types, $getResult);
1172: }
1173:
1174: /**
1175: * @param callable(Type $type): Type $getType
1176: */
1177: private function intersectTypes(callable $getType): Type
1178: {
1179: $operands = array_map($getType, $this->types);
1180: return TypeCombinator::intersect(...$operands);
1181: }
1182:
1183: public function toPhpDocNode(): TypeNode
1184: {
1185: $baseTypes = [];
1186: $typesToDescribe = [];
1187: $skipTypeNames = [];
1188:
1189: $nonEmptyStr = false;
1190: $nonFalsyStr = false;
1191: $isList = $this->isList()->yes();
1192: $isArray = $this->isArray()->yes();
1193: $isNonEmptyArray = $this->isIterableAtLeastOnce()->yes();
1194: $describedTypes = [];
1195:
1196: foreach ($this->getSortedTypes() as $i => $type) {
1197: if ($type instanceof AccessoryNonEmptyStringType
1198: || $type instanceof AccessoryLiteralStringType
1199: || $type instanceof AccessoryNumericStringType
1200: || $type instanceof AccessoryNonFalsyStringType
1201: || $type instanceof AccessoryLowercaseStringType
1202: || $type instanceof AccessoryUppercaseStringType
1203: ) {
1204: if ($type instanceof AccessoryNonFalsyStringType) {
1205: $nonFalsyStr = true;
1206: }
1207: if ($type instanceof AccessoryNonEmptyStringType) {
1208: $nonEmptyStr = true;
1209: }
1210: if ($nonEmptyStr && $nonFalsyStr) {
1211: // prevent redundant 'non-empty-string&non-falsy-string'
1212: foreach ($typesToDescribe as $key => $typeToDescribe) {
1213: if (!($typeToDescribe instanceof AccessoryNonEmptyStringType)) {
1214: continue;
1215: }
1216:
1217: unset($typesToDescribe[$key]);
1218: }
1219: }
1220:
1221: $typesToDescribe[$i] = $type;
1222: $skipTypeNames[] = 'string';
1223: continue;
1224: }
1225:
1226: if ($isList || $isArray) {
1227: if ($type instanceof ArrayType) {
1228: $keyType = $type->getKeyType();
1229: $valueType = $type->getItemType();
1230: if ($isList) {
1231: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
1232: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-list' : 'list');
1233: if (!$isMixedValueType) {
1234: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1235: $valueType->toPhpDocNode(),
1236: ]);
1237: } else {
1238: $describedTypes[$i] = $identifierTypeNode;
1239: }
1240: } else {
1241: $isMixedKeyType = $keyType instanceof MixedType && $keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$keyType->isExplicitMixed();
1242: $isMixedValueType = $valueType instanceof MixedType && $valueType->describe(VerbosityLevel::precise()) === 'mixed' && !$valueType->isExplicitMixed();
1243: $identifierTypeNode = new IdentifierTypeNode($isNonEmptyArray ? 'non-empty-array' : 'array');
1244: if (!$isMixedKeyType) {
1245: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1246: $keyType->toPhpDocNode(),
1247: $valueType->toPhpDocNode(),
1248: ]);
1249: } elseif (!$isMixedValueType) {
1250: $describedTypes[$i] = new GenericTypeNode($identifierTypeNode, [
1251: $valueType->toPhpDocNode(),
1252: ]);
1253: } else {
1254: $describedTypes[$i] = $identifierTypeNode;
1255: }
1256: }
1257: continue;
1258: } elseif ($type instanceof ConstantArrayType) {
1259: $constantArrayTypeNode = $type->toPhpDocNode();
1260: if ($constantArrayTypeNode instanceof ArrayShapeNode) {
1261: $newKind = $constantArrayTypeNode->kind;
1262: if ($isList) {
1263: if ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
1264: $newKind = ArrayShapeNode::KIND_NON_EMPTY_LIST;
1265: } else {
1266: $newKind = ArrayShapeNode::KIND_LIST;
1267: }
1268: } elseif ($isNonEmptyArray && !$type->isIterableAtLeastOnce()->yes()) {
1269: $newKind = ArrayShapeNode::KIND_NON_EMPTY_ARRAY;
1270: }
1271:
1272: if ($newKind !== $constantArrayTypeNode->kind) {
1273: if ($constantArrayTypeNode->sealed) {
1274: $constantArrayTypeNode = ArrayShapeNode::createSealed($constantArrayTypeNode->items, $newKind);
1275: } else {
1276: $constantArrayTypeNode = ArrayShapeNode::createUnsealed($constantArrayTypeNode->items, $constantArrayTypeNode->unsealedType, $newKind);
1277: }
1278: }
1279:
1280: $describedTypes[$i] = $constantArrayTypeNode;
1281: continue;
1282: }
1283: }
1284: if ($type instanceof NonEmptyArrayType || $type instanceof AccessoryArrayListType) {
1285: continue;
1286: }
1287: }
1288:
1289: if (!$type instanceof AccessoryType) {
1290: $baseTypes[$i] = $type;
1291: continue;
1292: }
1293:
1294: $accessoryPhpDocNode = $type->toPhpDocNode();
1295: if ($accessoryPhpDocNode instanceof IdentifierTypeNode && $accessoryPhpDocNode->name === '') {
1296: continue;
1297: }
1298:
1299: $typesToDescribe[$i] = $type;
1300: }
1301:
1302: foreach ($baseTypes as $i => $type) {
1303: $typeNode = $type->toPhpDocNode();
1304: if ($typeNode instanceof GenericTypeNode && $typeNode->type->name === 'array') {
1305: $nonEmpty = false;
1306: $typeName = 'array';
1307: foreach ($typesToDescribe as $j => $typeToDescribe) {
1308: if ($typeToDescribe instanceof AccessoryArrayListType) {
1309: $typeName = 'list';
1310: if (count($typeNode->genericTypes) > 1) {
1311: array_shift($typeNode->genericTypes);
1312: }
1313: } elseif ($typeToDescribe instanceof NonEmptyArrayType) {
1314: $nonEmpty = true;
1315: } else {
1316: continue;
1317: }
1318:
1319: unset($typesToDescribe[$j]);
1320: }
1321:
1322: if ($nonEmpty) {
1323: $typeName = 'non-empty-' . $typeName;
1324: }
1325:
1326: $describedTypes[$i] = new GenericTypeNode(
1327: new IdentifierTypeNode($typeName),
1328: $typeNode->genericTypes,
1329: );
1330: continue;
1331: }
1332:
1333: if ($typeNode instanceof IdentifierTypeNode && in_array($typeNode->name, $skipTypeNames, true)) {
1334: continue;
1335: }
1336:
1337: $describedTypes[$i] = $typeNode;
1338: }
1339:
1340: foreach ($typesToDescribe as $i => $typeToDescribe) {
1341: $describedTypes[$i] = $typeToDescribe->toPhpDocNode();
1342: }
1343:
1344: ksort($describedTypes);
1345:
1346: $describedTypes = array_values($describedTypes);
1347:
1348: if (count($describedTypes) === 1) {
1349: return $describedTypes[0];
1350: }
1351:
1352: return new IntersectionTypeNode($describedTypes);
1353: }
1354:
1355: }
1356: