1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PhpParser\Node\Identifier;
6: use PHPStan\Php\PhpVersion;
7: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
8: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
9: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
10: use PHPStan\Reflection\ClassMemberAccessAnswerer;
11: use PHPStan\Reflection\TrivialParametersAcceptor;
12: use PHPStan\Rules\Arrays\AllowedArrayKeysTypes;
13: use PHPStan\ShouldNotHappenException;
14: use PHPStan\TrinaryLogic;
15: use PHPStan\Turbo\ShadowedByTurboExtension;
16: use PHPStan\Type\Accessory\AccessoryArrayListType;
17: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
18: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
19: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
20: use PHPStan\Type\Accessory\AccessoryNumericStringType;
21: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
22: use PHPStan\Type\Accessory\HasOffsetType;
23: use PHPStan\Type\Accessory\HasOffsetValueType;
24: use PHPStan\Type\Accessory\NonEmptyArrayType;
25: use PHPStan\Type\Constant\ConstantArrayType;
26: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
27: use PHPStan\Type\Constant\ConstantBooleanType;
28: use PHPStan\Type\Constant\ConstantFloatType;
29: use PHPStan\Type\Constant\ConstantIntegerType;
30: use PHPStan\Type\Constant\ConstantStringType;
31: use PHPStan\Type\Generic\TemplateMixedType;
32: use PHPStan\Type\Generic\TemplateStrictMixedType;
33: use PHPStan\Type\Generic\TemplateType;
34: use PHPStan\Type\Generic\TemplateTypeMap;
35: use PHPStan\Type\Generic\TemplateTypeVariance;
36: use PHPStan\Type\Traits\ArrayTypeTrait;
37: use PHPStan\Type\Traits\MaybeCallableTypeTrait;
38: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
39: use PHPStan\Type\Traits\NonObjectTypeTrait;
40: use PHPStan\Type\Traits\UndecidedBooleanTypeTrait;
41: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
42: use PHPStan\Type\Traverser\UnsafeArrayStringKeyCastingTraverser;
43: use function array_map;
44: use function array_merge;
45: use function count;
46: use function in_array;
47: use function spl_object_id;
48: use function sprintf;
49: use function strtolower;
50: use function strtoupper;
51: use const CASE_LOWER;
52: use const CASE_UPPER;
53: use const PHP_INT_MAX;
54:
55: /** @api */
56: #[InstanceofDeprecated(insteadUse: 'Type::isArray() or Type::getArrays()')]
57: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ArrayType.cpp')]
58: class ArrayType implements Type
59: {
60:
61: use ArrayTypeTrait;
62: use MaybeCallableTypeTrait;
63: use NonObjectTypeTrait;
64: use UndecidedBooleanTypeTrait;
65: use UndecidedComparisonTypeTrait;
66: use NonGeneralizableTypeTrait;
67:
68: private const TRUNCATE_ACCESSORIES_LIMIT = 8;
69:
70: private Type $keyType;
71:
72: private ?Type $cachedIterableKeyType = null;
73:
74: private ?TrinaryLogic $isList = null;
75:
76: /** @api */
77: public function __construct(Type $keyType, private Type $itemType)
78: {
79: // Only a BenevolentUnionType describes with the surrounding parentheses of
80: // '(int|string)' / '(int|non-decimal-int-string)' (a plain union has no outer
81: // parens), so skip the expensive describe() call for every other key type.
82: if ($keyType instanceof BenevolentUnionType && in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
83: $keyType = new MixedType();
84: }
85: if ($keyType instanceof StrictMixedType && !$keyType instanceof TemplateStrictMixedType) {
86: $keyType = (new UnionType([new StringType(), new IntegerType()]))->toArrayKey();
87: }
88:
89: $this->keyType = $keyType;
90: }
91:
92: /** @var array<int, Type> */
93: private array $generalizedTypes = [];
94:
95: public function generalize(GeneralizePrecision $precision): Type
96: {
97: // Immutable, so it generalizes the same way every time - remembered
98: // because a member shared by several nested types is otherwise
99: // generalized once per path leading to it (see ConstantArrayType::generalize()).
100: return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
101: }
102:
103: public function getKeyType(): Type
104: {
105: return $this->keyType;
106: }
107:
108: public function getItemType(): Type
109: {
110: return $this->itemType;
111: }
112:
113: /**
114: * Build a same-kind array with new key/item types. Subclasses
115: * (e.g. {@see TemplateArrayType}) override this to preserve their
116: * extra metadata across array-mutating operations such as offset
117: * writes and unsets.
118: */
119: protected function withTypes(Type $keyType, Type $itemType): self
120: {
121: return new self($keyType, $itemType);
122: }
123:
124: public function getReferencedClasses(): array
125: {
126: return array_merge(
127: $this->keyType->getReferencedClasses(),
128: $this->getItemType()->getReferencedClasses(),
129: );
130: }
131:
132: public function getConstantArrays(): array
133: {
134: return [];
135: }
136:
137: public function accepts(Type $type, bool $strictTypes): AcceptsResult
138: {
139: if ($type instanceof CompoundType) {
140: return $type->isAcceptedBy($this, $strictTypes);
141: }
142:
143: if ($type instanceof ConstantArrayType) {
144: $result = AcceptsResult::createYes();
145: $thisKeyType = $this->keyType;
146: $itemType = $this->getItemType();
147: foreach ($type->getKeyTypes() as $i => $keyType) {
148: $valueType = $type->getValueTypes()[$i];
149: $acceptsKey = $thisKeyType->accepts($keyType, $strictTypes);
150: $acceptsValue = $itemType->accepts($valueType, $strictTypes);
151: $result = $result->and($acceptsKey)->and($acceptsValue);
152: }
153:
154: return $result;
155: }
156:
157: if ($type instanceof ArrayType) {
158: return $this->getItemType()->accepts($type->getItemType(), $strictTypes)
159: ->and($this->keyType->accepts($type->keyType, $strictTypes));
160: }
161:
162: return AcceptsResult::createNo();
163: }
164:
165: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
166: {
167: if ($type instanceof self || $type instanceof ConstantArrayType) {
168: $result = $this->getItemType()->isSuperTypeOf($type->getItemType())
169: ->and($this->getIterableKeyType()->isSuperTypeOf($type->getIterableKeyType()));
170: if (
171: $result->no()
172: && $type->isConstantArray()->yes()
173: && !$type->isIterableAtLeastOnce()->yes()
174: ) {
175: // A possibly-empty constant array admits `[]`, a subtype of every
176: // array type, so the relationship is at worst `maybe`, never `no`.
177: return IsSuperTypeOfResult::createMaybe();
178: }
179: return $result;
180: }
181:
182: if ($type instanceof CompoundType) {
183: return $type->isSubTypeOf($this);
184: }
185:
186: return IsSuperTypeOfResult::createNo();
187: }
188:
189: public function equals(Type $type): bool
190: {
191: return $type instanceof self
192: && $this->getItemType()->equals($type->getIterableValueType())
193: && $this->keyType->equals($type->keyType);
194: }
195:
196: public function describe(VerbosityLevel $level): string
197: {
198: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
199: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
200:
201: $valueHandler = function () use ($level, $isMixedKeyType, $isMixedItemType): string {
202: if ($isMixedKeyType || $this->keyType instanceof NeverType) {
203: if ($isMixedItemType || $this->itemType instanceof NeverType) {
204: return 'array';
205: }
206:
207: return sprintf('array<%s>', $this->itemType->describe($level));
208: }
209:
210: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
211: };
212:
213: return $level->handle(
214: $valueHandler,
215: $valueHandler,
216: function () use ($level, $isMixedKeyType, $isMixedItemType): string {
217: if ($isMixedKeyType) {
218: if ($isMixedItemType) {
219: return 'array';
220: }
221:
222: return sprintf('array<%s>', $this->itemType->describe($level));
223: }
224:
225: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
226: },
227: );
228: }
229:
230: public function generalizeValues(): self
231: {
232: return new self($this->keyType, $this->itemType->generalize(GeneralizePrecision::lessSpecific()));
233: }
234:
235: public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
236: {
237: return $this->getKeysArray();
238: }
239:
240: public function getKeysArray(): Type
241: {
242: return TypeCombinator::intersect(new self(new IntegerType(), $this->getIterableKeyType()), new AccessoryArrayListType());
243: }
244:
245: public function getValuesArray(): Type
246: {
247: return TypeCombinator::intersect(new self(new IntegerType(), $this->itemType), new AccessoryArrayListType());
248: }
249:
250: public function isIterableAtLeastOnce(): TrinaryLogic
251: {
252: return TrinaryLogic::createMaybe();
253: }
254:
255: public function getArraySize(): Type
256: {
257: return IntegerRangeType::fromInterval(0, null);
258: }
259:
260: public function getIterableKeyType(): Type
261: {
262: if ($this->cachedIterableKeyType !== null) {
263: return $this->cachedIterableKeyType;
264: }
265: $keyType = $this->keyType;
266: if ($keyType instanceof MixedType && !$keyType instanceof TemplateMixedType) {
267: $keyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
268: }
269: if ($keyType instanceof StrictMixedType) {
270: $keyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
271: }
272:
273: return $this->cachedIterableKeyType = UnsafeArrayStringKeyCastingTraverser::castKeyType($keyType);
274: }
275:
276: public function getFirstIterableKeyType(): Type
277: {
278: return $this->getIterableKeyType();
279: }
280:
281: public function getLastIterableKeyType(): Type
282: {
283: return $this->getIterableKeyType();
284: }
285:
286: public function getIterableValueType(): Type
287: {
288: return $this->getItemType();
289: }
290:
291: public function getFirstIterableValueType(): Type
292: {
293: return $this->getItemType();
294: }
295:
296: public function getLastIterableValueType(): Type
297: {
298: return $this->getItemType();
299: }
300:
301: public function isConstantArray(): TrinaryLogic
302: {
303: return TrinaryLogic::createNo();
304: }
305:
306: public function isList(): TrinaryLogic
307: {
308: if ($this->isList === null) {
309: if (IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($this->getKeyType())->no()) {
310: return $this->isList = TrinaryLogic::createNo();
311: }
312:
313: if ($this->getKeyType()->isSuperTypeOf(new ConstantIntegerType(0))->no()) {
314: return $this->isList = TrinaryLogic::createNo();
315: }
316:
317: return $this->isList = TrinaryLogic::createMaybe();
318: }
319:
320: return $this->isList;
321: }
322:
323: public function isConstantValue(): TrinaryLogic
324: {
325: return TrinaryLogic::createNo();
326: }
327:
328: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
329: {
330: if ($type->isInteger()->yes()) {
331: return new ConstantBooleanType(false);
332: }
333:
334: return new BooleanType();
335: }
336:
337: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
338: {
339: $offsetArrayKeyType = $offsetType->toArrayKey();
340: if ($offsetArrayKeyType instanceof ErrorType) {
341: $allowedArrayKeys = AllowedArrayKeysTypes::getType();
342: $offsetArrayKeyType = TypeCombinator::intersect($allowedArrayKeys, $offsetType)->toArrayKey();
343: if ($offsetArrayKeyType instanceof NeverType) {
344: return TrinaryLogic::createNo();
345: }
346: }
347: $offsetType = $offsetArrayKeyType;
348:
349: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
350: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
351: ) {
352: return TrinaryLogic::createNo();
353: }
354:
355: return TrinaryLogic::createMaybe();
356: }
357:
358: public function getOffsetValueType(Type $offsetType): Type
359: {
360: $offsetType = $offsetType->toArrayKey();
361: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
362: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
363: ) {
364: return new ErrorType();
365: }
366:
367: $type = $this->getItemType();
368: if ($type instanceof ErrorType) {
369: return new MixedType();
370: }
371:
372: return $type;
373: }
374:
375: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
376: {
377: if ($offsetType === null) {
378: $isKeyTypeInteger = $this->keyType->isInteger();
379: if ($isKeyTypeInteger->no()) {
380: $offsetType = new IntegerType();
381: } elseif ($isKeyTypeInteger->yes()) {
382: /** @var list<ConstantIntegerType> $constantScalars */
383: $constantScalars = $this->keyType->getConstantScalarTypes();
384: if (count($constantScalars) > 0) {
385: $offsetTypes = $constantScalars;
386: foreach ($constantScalars as $constantScalar) {
387: // an offset past PHP_INT_MAX cannot be assigned, so it's not a possible key
388: if ($constantScalar->getValue() === PHP_INT_MAX) {
389: continue;
390: }
391:
392: $offsetTypes[] = new ConstantIntegerType($constantScalar->getValue() + 1);
393: }
394:
395: $offsetType = TypeCombinator::union(...$offsetTypes);
396: } else {
397: $offsetType = $this->keyType;
398: }
399: } else {
400: $integerTypes = [];
401: TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use (&$integerTypes): Type {
402: if ($type instanceof UnionType) {
403: return $traverse($type);
404: }
405:
406: $isInteger = $type->isInteger();
407: if ($isInteger->yes()) {
408: $integerTypes[] = $type;
409: }
410:
411: return $type;
412: });
413: if (count($integerTypes) === 0) {
414: $offsetType = $this->keyType;
415: } else {
416: $offsetType = TypeCombinator::union(...$integerTypes);
417: }
418: }
419: } else {
420: $offsetType = $offsetType->toArrayKey();
421: }
422:
423: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
424: if ($offsetType->isSuperTypeOf($this->keyType)->yes()) {
425: $builder = ConstantArrayTypeBuilder::createEmpty();
426: $builder->setOffsetValueType($offsetType, $valueType);
427: return $builder->getArray();
428: }
429:
430: return new IntersectionType([
431: $this->withTypes(
432: $this->unionKeyTypeWithConstantOffset($offsetType),
433: TypeCombinator::union($this->itemType, $valueType),
434: ),
435: new HasOffsetValueType($offsetType, $valueType),
436: new NonEmptyArrayType(),
437: ]);
438: }
439:
440: return new IntersectionType([
441: $this->withTypes(
442: TypeCombinator::union($this->keyType, $offsetType),
443: $unionValues ? TypeCombinator::union($this->itemType, $valueType) : $valueType,
444: ),
445: new NonEmptyArrayType(),
446: ]);
447: }
448:
449: /**
450: * The key type with a constant offset written into the array.
451: *
452: * A key union that already holds the offset is handed back as it is. Unioning would
453: * rebuild the same members, and an array keyed by a union of a few hundred literals
454: * pays that rebuild for every key written. The array type - and its key union - lives
455: * on across the writes, so the membership check pays for the union's finite value
456: * index once; asking it of every union TypeCombinator sees would build that index for
457: * short-lived unions that are never asked again.
458: */
459: private function unionKeyTypeWithConstantOffset(Type $offsetType): Type
460: {
461: if (
462: $this->keyType instanceof UnionType
463: && !$this->keyType instanceof BenevolentUnionType
464: && !$this->keyType instanceof TemplateType
465: && $this->keyType->isSuperTypeOf($offsetType)->yes()
466: ) {
467: return $this->keyType;
468: }
469:
470: return TypeCombinator::union($this->keyType, $offsetType);
471: }
472:
473: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
474: {
475: if ($this->itemType->isConstantArray()->yes() && $valueType->isConstantArray()->yes()) {
476: $newItemTypes = [];
477:
478: $itemConstantArrays = $this->itemType->getConstantArrays();
479: foreach ($valueType->getConstantArrays() as $constArray) {
480: if ($constArray->getOptionalKeys() !== [] && count($itemConstantArrays) === 1) {
481: // A written shape with optional keys is not all-or-nothing: each
482: // optional key may or may not be present on its own, so it is
483: // written as optional (present keys keep their certainty, the
484: // value unions with what the key held) instead of once with every
485: // key required and once with every optional key unset.
486: $builder = ConstantArrayTypeBuilder::createFromConstantArray($itemConstantArrays[0]);
487: foreach ($constArray->getKeyTypes() as $i => $keyType) {
488: $builder->setOffsetValueType($keyType, $constArray->getOffsetValueType($keyType), $constArray->isOptionalKey($i));
489: }
490: $newItemTypes[] = TypeCombinator::intersect($builder->getArray(), ...TypeUtils::getAccessoryTypes($this->itemType));
491: continue;
492: }
493:
494: $newItemType = $this->itemType;
495: $optionalKeyTypes = [];
496: foreach ($constArray->getKeyTypes() as $i => $keyType) {
497: $newItemType = $newItemType->setExistingOffsetValueType($keyType, $constArray->getOffsetValueType($keyType));
498:
499: if (!$constArray->isOptionalKey($i)) {
500: continue;
501: }
502:
503: $optionalKeyTypes[] = $keyType;
504: }
505: $newItemTypes[] = $newItemType;
506:
507: if ($optionalKeyTypes === []) {
508: continue;
509: }
510:
511: foreach ($optionalKeyTypes as $keyType) {
512: $newItemType = $newItemType->unsetOffset($keyType);
513: }
514: $newItemTypes[] = $newItemType;
515: }
516:
517: $newItemType = TypeCombinator::union(...$newItemTypes);
518: if ($newItemType !== $this->itemType) {
519: return new self(
520: $this->keyType,
521: $newItemType,
522: );
523: }
524: }
525:
526: return new self(
527: $this->keyType,
528: TypeCombinator::union($this->itemType, $valueType),
529: );
530: }
531:
532: public function unsetOffset(Type $offsetType): Type
533: {
534: $offsetType = $offsetType->toArrayKey();
535:
536: if (
537: ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
538: && !$this->keyType->isSuperTypeOf($offsetType)->no()
539: ) {
540: $keyType = TypeCombinator::remove($this->keyType, $offsetType);
541: if ($keyType instanceof NeverType) {
542: return new ConstantArrayType([], []);
543: }
544:
545: return new self($keyType, $this->itemType);
546: }
547:
548: return $this;
549: }
550:
551: public function fillKeysArray(Type $valueType): Type
552: {
553: $itemType = $this->getItemType();
554: if ($itemType->isInteger()->no()) {
555: $stringKeyType = $itemType->toString();
556: if ($stringKeyType instanceof ErrorType) {
557: return $stringKeyType;
558: }
559:
560: return new ArrayType($stringKeyType->toArrayKey(), $valueType);
561: }
562:
563: return new ArrayType($itemType->toArrayKey(), $valueType);
564: }
565:
566: public function flipArray(): Type
567: {
568: return new self($this->getIterableValueType()->toArrayKey(), $this->getIterableKeyType());
569: }
570:
571: public function intersectKeyArray(Type $otherArraysType): Type
572: {
573: $isKeySuperType = $otherArraysType->getIterableKeyType()->isSuperTypeOf($this->getIterableKeyType());
574: if ($isKeySuperType->no()) {
575: return ConstantArrayTypeBuilder::createEmpty()->getArray();
576: }
577:
578: if ($isKeySuperType->yes()) {
579: return $this;
580: }
581:
582: $constantArrays = $otherArraysType->getConstantArrays();
583: if (count($constantArrays) > 0) {
584: // When the other operand is one or more array shapes with a known
585: // sealedness, the result is a (possibly unsealed) array shape too:
586: // it can only contain the keys present in those shapes, each
587: // optional because the general first array may or may not have it.
588: $allSealednessKnown = true;
589: foreach ($constantArrays as $constantArray) {
590: if ($constantArray->isUnsealed()->maybe()) {
591: $allSealednessKnown = false;
592: break;
593: }
594: }
595:
596: if ($allSealednessKnown) {
597: $results = [];
598: foreach ($constantArrays as $constantArray) {
599: $results[] = $this->intersectConstantArrayShape($constantArray);
600: }
601:
602: return TypeCombinator::union(...$results);
603: }
604: }
605:
606: return $this->withTypes($otherArraysType->getIterableKeyType(), $this->getIterableValueType());
607: }
608:
609: private function intersectConstantArrayShape(ConstantArrayType $constantArray): Type
610: {
611: $builder = ConstantArrayTypeBuilder::createEmpty();
612:
613: $valueType = $this->getIterableValueType();
614: $keyType = $this->getIterableKeyType();
615: foreach ($constantArray->getKeyTypes() as $shapeKeyType) {
616: if (TypeCombinator::intersect($shapeKeyType, $keyType) instanceof NeverType) {
617: continue;
618: }
619: $builder->setOffsetValueType($shapeKeyType, $valueType, true);
620: }
621:
622: $unsealed = $constantArray->getUnsealedTypes();
623: if ($constantArray->isUnsealed()->yes() && $unsealed !== null) {
624: $narrowedUnsealedKey = TypeCombinator::intersect($unsealed[0], $keyType);
625: if (!$narrowedUnsealedKey instanceof NeverType) {
626: $builder->makeUnsealed($narrowedUnsealedKey, $valueType);
627: }
628: }
629:
630: return $builder->getArray();
631: }
632:
633: public function popArray(): Type
634: {
635: return $this;
636: }
637:
638: public function reverseArray(TrinaryLogic $preserveKeys): Type
639: {
640: return $this;
641: }
642:
643: public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Type
644: {
645: $strict ??= TrinaryLogic::createMaybe();
646: if ($strict->yes() && $this->getIterableValueType()->isSuperTypeOf($needleType)->no()) {
647: return new ConstantBooleanType(false);
648: }
649:
650: return TypeCombinator::union($this->getIterableKeyType(), new ConstantBooleanType(false));
651: }
652:
653: public function shiftArray(): Type
654: {
655: return $this;
656: }
657:
658: public function shuffleArray(): Type
659: {
660: return new IntersectionType([$this->withTypes(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $this->itemType), new AccessoryArrayListType()]);
661: }
662:
663: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
664: {
665: if ((new ConstantIntegerType(0))->isSuperTypeOf($lengthType)->yes()) {
666: return new ConstantArrayType([], []);
667: }
668:
669: if ($preserveKeys->no() && $this->keyType->isInteger()->yes()) {
670: return new IntersectionType([$this->withTypes(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $this->itemType), new AccessoryArrayListType()]);
671: }
672:
673: return $this;
674: }
675:
676: public function spliceArray(Type $offsetType, Type $lengthType, Type $replacementType): Type
677: {
678: $replacementArrayType = $replacementType->toArray();
679: $replacementArrayTypeIsIterableAtLeastOnce = $replacementArrayType->isIterableAtLeastOnce();
680:
681: if ((new ConstantIntegerType(0))->isSuperTypeOf($offsetType)->yes() && $lengthType->isNull()->yes() && $replacementArrayTypeIsIterableAtLeastOnce->no()) {
682: return new ConstantArrayType([], []);
683: }
684:
685: $existingArrayKeyType = $this->getIterableKeyType();
686: $keyType = TypeTraverser::map($existingArrayKeyType, static function (Type $type, callable $traverse): Type {
687: if ($type instanceof UnionType) {
688: return $traverse($type);
689: }
690:
691: if ($type->isInteger()->yes()) {
692: return IntegerRangeType::createAllGreaterThanOrEqualTo(0);
693: }
694:
695: return $type;
696: });
697:
698: $arrayType = $this->withTypes(
699: TypeCombinator::union($keyType, $replacementArrayType->getKeysArray()->getIterableKeyType()),
700: TypeCombinator::union($this->getIterableValueType(), $replacementArrayType->getIterableValueType()),
701: );
702:
703: $accessories = [];
704: if ($replacementArrayTypeIsIterableAtLeastOnce->yes()) {
705: $accessories[] = new NonEmptyArrayType();
706: }
707: if ($existingArrayKeyType->isInteger()->yes()) {
708: $accessories[] = new AccessoryArrayListType();
709: }
710: if (count($accessories) > 0) {
711: $accessories[] = $arrayType;
712:
713: return new IntersectionType($accessories);
714: }
715:
716: return $arrayType;
717: }
718:
719: public function makeListMaybe(): Type
720: {
721: // `ArrayType` doesn't carry list-ness on its own — that's an
722: // `AccessoryArrayListType` in an enclosing `IntersectionType`.
723: return $this;
724: }
725:
726: public function truncateListToSize(Type $sizeType): Type
727: {
728: [$min, $max] = ConstantArrayType::extractTruncateListBounds($sizeType);
729:
730: // `isList()` is deliberately NOT checked here — see the matching
731: // note on `ConstantArrayType::truncateListToSize`. The call site
732: // has already established outer list-ness.
733: if (
734: $min === null
735: || $min >= ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
736: || !$this->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($max ?? $min) - 1))->yes()
737: ) {
738: return TypeCombinator::intersect($this, new NonEmptyArrayType());
739: }
740:
741: if ($max !== null) {
742: // Bounded range — `ArrayType` doesn't carry per-offset types, so
743: // rebuild via the same CAT builder logic as `ConstantArrayType`.
744: // The values come from `$this->getOffsetValueType()` (which on a
745: // general `ArrayType` collapses to the iterable value type).
746: if ($max - $min > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
747: return TypeCombinator::intersect($this, new NonEmptyArrayType());
748: }
749:
750: $builder = ConstantArrayTypeBuilder::createEmpty();
751: for ($i = 0; $i < $min; $i++) {
752: $offsetType = new ConstantIntegerType($i);
753: $builder->setOffsetValueType($offsetType, $this->getOffsetValueType($offsetType), false);
754: }
755: for ($i = $min; $i < $max; $i++) {
756: $offsetType = new ConstantIntegerType($i);
757: $builder->setOffsetValueType($offsetType, $this->getOffsetValueType($offsetType), true);
758: }
759:
760: $builtArray = $builder->getArray();
761: if (!$builder->isList()) {
762: $constantArrays = $builtArray->getConstantArrays();
763: if (count($constantArrays) === 1) {
764: $builtArray = $constantArrays[0]->makeList();
765: }
766: }
767:
768: return $builtArray;
769: }
770:
771: // Unbounded max on a general `ArrayType` list: we can't enumerate the
772: // trailing entries, so anchor the lower bound with
773: // `HasOffsetValueType` accessories (skipping offset 0 — already
774: // implied by `NonEmptyArrayType`).
775: $intersection = [$this, new NonEmptyArrayType()];
776: $zero = new ConstantIntegerType(0);
777: $added = 0;
778: for ($i = 0; $i < $min; $i++) {
779: $offsetType = new ConstantIntegerType($i);
780: if ($zero->isSuperTypeOf($offsetType)->yes()) {
781: continue;
782: }
783: if ($added > self::TRUNCATE_ACCESSORIES_LIMIT) {
784: break;
785: }
786:
787: $intersection[] = new HasOffsetValueType($offsetType, $this->getOffsetValueType($offsetType));
788: $added++;
789: }
790:
791: return TypeCombinator::intersect(...$intersection);
792: }
793:
794: public function mapValueType(callable $cb): Type
795: {
796: return $this->withTypes($this->keyType, $cb($this->getItemType()));
797: }
798:
799: public function mapKeyType(callable $cb): Type
800: {
801: return $this->withTypes($cb($this->keyType), $this->getItemType());
802: }
803:
804: public function makeAllArrayKeysOptional(): Type
805: {
806: // `ArrayType` already models arbitrary key subsets.
807: return $this;
808: }
809:
810: public function changeKeyCaseArray(?int $case): Type
811: {
812: $newKeyType = TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use ($case): Type {
813: if ($type instanceof UnionType) {
814: return $traverse($type);
815: }
816:
817: $constantStrings = $type->getConstantStrings();
818: if (count($constantStrings) > 0) {
819: return TypeCombinator::union(
820: ...array_map(
821: static fn (ConstantStringType $type): Type => self::foldConstantStringKeyCase($type, $case),
822: $constantStrings,
823: ),
824: );
825: }
826:
827: if ($type->isString()->yes()) {
828: $types = [new StringType()];
829: if ($type->isNonFalsyString()->yes()) {
830: $types[] = new AccessoryNonFalsyStringType();
831: } elseif ($type->isNonEmptyString()->yes()) {
832: $types[] = new AccessoryNonEmptyStringType();
833: }
834: if ($type->isNumericString()->yes()) {
835: $types[] = new AccessoryNumericStringType();
836: }
837: if ($case === CASE_LOWER) {
838: $types[] = new AccessoryLowercaseStringType();
839: } elseif ($case === CASE_UPPER) {
840: $types[] = new AccessoryUppercaseStringType();
841: }
842:
843: if (count($types) === 1) {
844: return $types[0];
845: }
846: return new IntersectionType($types);
847: }
848:
849: return $type;
850: });
851:
852: return $this->withTypes($newKeyType, $this->getItemType());
853: }
854:
855: public function filterArrayRemovingFalsey(): Type
856: {
857: $falseyTypes = StaticTypeFactory::falsey();
858: $valueType = TypeCombinator::remove($this->getItemType(), $falseyTypes);
859: if ($valueType instanceof NeverType) {
860: return new ConstantArrayType([], []);
861: }
862:
863: return $this->withTypes($this->keyType, $valueType);
864: }
865:
866: private static function foldConstantStringKeyCase(ConstantStringType $type, ?int $case): Type
867: {
868: if ($case === CASE_LOWER) {
869: return new ConstantStringType(strtolower($type->getValue()));
870: }
871: if ($case === CASE_UPPER) {
872: return new ConstantStringType(strtoupper($type->getValue()));
873: }
874:
875: return TypeCombinator::union(
876: new ConstantStringType(strtolower($type->getValue())),
877: new ConstantStringType(strtoupper($type->getValue())),
878: );
879: }
880:
881: public function isCallable(): TrinaryLogic
882: {
883: if (!$this->itemType->isString()->no()) {
884: return TrinaryLogic::createMaybe();
885: }
886:
887: // StrictMixedType denies isString() even though it is a supertype of
888: // string, so a value of that item type can still be the method name
889: // of a callable array.
890: if ((new StringType())->isSuperTypeOf($this->itemType)->maybe()) {
891: return TrinaryLogic::createMaybe();
892: }
893:
894: return TrinaryLogic::createNo();
895: }
896:
897: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
898: {
899: if ($this->isCallable()->no()) {
900: throw new ShouldNotHappenException();
901: }
902:
903: return [new TrivialParametersAcceptor()];
904: }
905:
906: public function toInteger(): Type
907: {
908: return new UnionType([
909: new ConstantIntegerType(0),
910: new ConstantIntegerType(1),
911: ]);
912: }
913:
914: public function toFloat(): Type
915: {
916: return new UnionType([
917: new ConstantFloatType(0.0),
918: new ConstantFloatType(1.0),
919: ]);
920: }
921:
922: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
923: {
924: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
925: return $receivedType->inferTemplateTypesOn($this);
926: }
927:
928: if ($receivedType->isArray()->yes()) {
929: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
930: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
931:
932: return $keyTypeMap->union($itemTypeMap);
933: }
934:
935: return TemplateTypeMap::createEmpty();
936: }
937:
938: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
939: {
940: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
941:
942: return array_merge(
943: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
944: $this->getItemType()->getReferencedTemplateTypes($variance),
945: );
946: }
947:
948: public function traverse(callable $cb): Type
949: {
950: $keyType = $cb($this->keyType);
951: $itemType = $cb($this->itemType);
952:
953: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
954: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
955: return new ConstantArrayType([], []);
956: }
957:
958: return $this->withTypes($keyType, $itemType);
959: }
960:
961: return $this;
962: }
963:
964: public function toPhpDocNode(): TypeNode
965: {
966: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
967: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
968:
969: if ($isMixedKeyType) {
970: if ($isMixedItemType) {
971: return new IdentifierTypeNode('array');
972: }
973:
974: return new GenericTypeNode(
975: new IdentifierTypeNode('array'),
976: [
977: $this->itemType->toPhpDocNode(),
978: ],
979: );
980: }
981:
982: return new GenericTypeNode(
983: new IdentifierTypeNode('array'),
984: [
985: $this->keyType->toPhpDocNode(),
986: $this->itemType->toPhpDocNode(),
987: ],
988: );
989: }
990:
991: public function toNativePhpTypeNode(NativeTypePosition $position)
992: {
993: return $position->isArrayAllowed() ? new Identifier('array') : null;
994: }
995:
996: public function traverseSimultaneously(Type $right, callable $cb): Type
997: {
998: $keyType = $cb($this->keyType, $right->getIterableKeyType());
999: $itemType = $cb($this->itemType, $right->getIterableValueType());
1000:
1001: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
1002: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
1003: return new ConstantArrayType([], []);
1004: }
1005:
1006: return $this->withTypes($keyType, $itemType);
1007: }
1008:
1009: return $this;
1010: }
1011:
1012: public function tryRemove(Type $typeToRemove): ?Type
1013: {
1014: if ($typeToRemove->isSuperTypeOf(new ConstantArrayType([], []))->yes()) {
1015: return TypeCombinator::intersect($this, new NonEmptyArrayType());
1016: }
1017:
1018: if ($typeToRemove instanceof NonEmptyArrayType) {
1019: return new ConstantArrayType([], []);
1020: }
1021:
1022: if ($typeToRemove instanceof HasOffsetType) {
1023: return $this->unsetOffset($typeToRemove->getOffsetType());
1024: }
1025:
1026: if (
1027: $typeToRemove instanceof HasOffsetValueType
1028: && $typeToRemove->getValueType()->isSuperTypeOf($this->itemType)->yes()
1029: ) {
1030: return $this->unsetOffset($typeToRemove->getOffsetType());
1031: }
1032:
1033: return null;
1034: }
1035:
1036: public function getFiniteTypes(): array
1037: {
1038: return [];
1039: }
1040:
1041: public function hasTemplateOrLateResolvableType(): bool
1042: {
1043: return $this->keyType->hasTemplateOrLateResolvableType() || $this->itemType->hasTemplateOrLateResolvableType();
1044: }
1045:
1046: }
1047: