1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\Php\PhpVersion;
6: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
7: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
8: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
9: use PHPStan\Reflection\ClassMemberAccessAnswerer;
10: use PHPStan\Reflection\TrivialParametersAcceptor;
11: use PHPStan\ShouldNotHappenException;
12: use PHPStan\TrinaryLogic;
13: use PHPStan\Type\Accessory\AccessoryArrayListType;
14: use PHPStan\Type\Accessory\HasOffsetType;
15: use PHPStan\Type\Accessory\HasOffsetValueType;
16: use PHPStan\Type\Accessory\NonEmptyArrayType;
17: use PHPStan\Type\Constant\ConstantArrayType;
18: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
19: use PHPStan\Type\Constant\ConstantBooleanType;
20: use PHPStan\Type\Constant\ConstantFloatType;
21: use PHPStan\Type\Constant\ConstantIntegerType;
22: use PHPStan\Type\Constant\ConstantStringType;
23: use PHPStan\Type\Generic\TemplateMixedType;
24: use PHPStan\Type\Generic\TemplateTypeMap;
25: use PHPStan\Type\Generic\TemplateTypeVariance;
26: use PHPStan\Type\Traits\MaybeCallableTypeTrait;
27: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
28: use PHPStan\Type\Traits\NonObjectTypeTrait;
29: use PHPStan\Type\Traits\UndecidedBooleanTypeTrait;
30: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
31: use function array_merge;
32: use function count;
33: use function sprintf;
34:
35: /** @api */
36: class ArrayType implements Type
37: {
38:
39: use MaybeCallableTypeTrait;
40: use NonObjectTypeTrait;
41: use UndecidedBooleanTypeTrait;
42: use UndecidedComparisonTypeTrait;
43: use NonGeneralizableTypeTrait;
44:
45: private Type $keyType;
46:
47: /** @api */
48: public function __construct(Type $keyType, private Type $itemType)
49: {
50: if ($keyType->describe(VerbosityLevel::value()) === '(int|string)') {
51: $keyType = new MixedType();
52: }
53: $this->keyType = $keyType;
54: }
55:
56: public function getKeyType(): Type
57: {
58: return $this->keyType;
59: }
60:
61: public function getItemType(): Type
62: {
63: return $this->itemType;
64: }
65:
66: /**
67: * @return string[]
68: */
69: public function getReferencedClasses(): array
70: {
71: return array_merge(
72: $this->keyType->getReferencedClasses(),
73: $this->getItemType()->getReferencedClasses(),
74: );
75: }
76:
77: public function getObjectClassNames(): array
78: {
79: return [];
80: }
81:
82: public function getObjectClassReflections(): array
83: {
84: return [];
85: }
86:
87: public function getArrays(): array
88: {
89: return [$this];
90: }
91:
92: public function getConstantArrays(): array
93: {
94: return [];
95: }
96:
97: public function accepts(Type $type, bool $strictTypes): TrinaryLogic
98: {
99: return $this->acceptsWithReason($type, $strictTypes)->result;
100: }
101:
102: public function acceptsWithReason(Type $type, bool $strictTypes): AcceptsResult
103: {
104: if ($type instanceof CompoundType) {
105: return $type->isAcceptedWithReasonBy($this, $strictTypes);
106: }
107:
108: if ($type instanceof ConstantArrayType) {
109: $result = AcceptsResult::createYes();
110: $thisKeyType = $this->keyType;
111: $itemType = $this->getItemType();
112: foreach ($type->getKeyTypes() as $i => $keyType) {
113: $valueType = $type->getValueTypes()[$i];
114: $acceptsKey = $thisKeyType->acceptsWithReason($keyType, $strictTypes);
115: $acceptsValue = $itemType->acceptsWithReason($valueType, $strictTypes);
116: $result = $result->and($acceptsKey)->and($acceptsValue);
117: }
118:
119: return $result;
120: }
121:
122: if ($type instanceof ArrayType) {
123: return $this->getItemType()->acceptsWithReason($type->getItemType(), $strictTypes)
124: ->and($this->keyType->acceptsWithReason($type->keyType, $strictTypes));
125: }
126:
127: return AcceptsResult::createNo();
128: }
129:
130: public function isSuperTypeOf(Type $type): TrinaryLogic
131: {
132: if ($type instanceof self) {
133: return $this->getItemType()->isSuperTypeOf($type->getItemType())
134: ->and($this->getIterableKeyType()->isSuperTypeOf($type->getIterableKeyType()));
135: }
136:
137: if ($type instanceof CompoundType) {
138: return $type->isSubTypeOf($this);
139: }
140:
141: return TrinaryLogic::createNo();
142: }
143:
144: public function equals(Type $type): bool
145: {
146: return $type instanceof self
147: && $type->isConstantArray()->no()
148: && $this->getItemType()->equals($type->getIterableValueType())
149: && $this->keyType->equals($type->keyType);
150: }
151:
152: public function describe(VerbosityLevel $level): string
153: {
154: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed';
155: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed';
156:
157: $valueHandler = function () use ($level, $isMixedKeyType, $isMixedItemType): string {
158: if ($isMixedKeyType || $this->keyType instanceof NeverType) {
159: if ($isMixedItemType || $this->itemType instanceof NeverType) {
160: return 'array';
161: }
162:
163: return sprintf('array<%s>', $this->itemType->describe($level));
164: }
165:
166: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
167: };
168:
169: return $level->handle(
170: $valueHandler,
171: $valueHandler,
172: function () use ($level, $isMixedKeyType, $isMixedItemType): string {
173: if ($isMixedKeyType) {
174: if ($isMixedItemType) {
175: return 'array';
176: }
177:
178: return sprintf('array<%s>', $this->itemType->describe($level));
179: }
180:
181: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
182: },
183: );
184: }
185:
186: /**
187: * @deprecated
188: */
189: public function generalizeKeys(): self
190: {
191: return new self($this->keyType->generalize(GeneralizePrecision::lessSpecific()), $this->itemType);
192: }
193:
194: public function generalizeValues(): self
195: {
196: return new self($this->keyType, $this->itemType->generalize(GeneralizePrecision::lessSpecific()));
197: }
198:
199: public function getKeysArray(): Type
200: {
201: return AccessoryArrayListType::intersectWith(new self(new IntegerType(), $this->getIterableKeyType()));
202: }
203:
204: public function getValuesArray(): Type
205: {
206: return AccessoryArrayListType::intersectWith(new self(new IntegerType(), $this->itemType));
207: }
208:
209: public function isIterable(): TrinaryLogic
210: {
211: return TrinaryLogic::createYes();
212: }
213:
214: public function isIterableAtLeastOnce(): TrinaryLogic
215: {
216: return TrinaryLogic::createMaybe();
217: }
218:
219: public function getArraySize(): Type
220: {
221: return IntegerRangeType::fromInterval(0, null);
222: }
223:
224: public function getIterableKeyType(): Type
225: {
226: $keyType = $this->keyType;
227: if ($keyType instanceof MixedType && !$keyType instanceof TemplateMixedType) {
228: return new BenevolentUnionType([new IntegerType(), new StringType()]);
229: }
230: if ($keyType instanceof StrictMixedType) {
231: return new BenevolentUnionType([new IntegerType(), new StringType()]);
232: }
233:
234: return $keyType;
235: }
236:
237: public function getFirstIterableKeyType(): Type
238: {
239: return $this->getIterableKeyType();
240: }
241:
242: public function getLastIterableKeyType(): Type
243: {
244: return $this->getIterableKeyType();
245: }
246:
247: public function getIterableValueType(): Type
248: {
249: return $this->getItemType();
250: }
251:
252: public function getFirstIterableValueType(): Type
253: {
254: return $this->getItemType();
255: }
256:
257: public function getLastIterableValueType(): Type
258: {
259: return $this->getItemType();
260: }
261:
262: public function isArray(): TrinaryLogic
263: {
264: return TrinaryLogic::createYes();
265: }
266:
267: public function isConstantArray(): TrinaryLogic
268: {
269: return TrinaryLogic::createNo();
270: }
271:
272: public function isOversizedArray(): TrinaryLogic
273: {
274: return TrinaryLogic::createMaybe();
275: }
276:
277: public function isList(): TrinaryLogic
278: {
279: if (IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($this->getKeyType())->no()) {
280: return TrinaryLogic::createNo();
281: }
282:
283: return TrinaryLogic::createMaybe();
284: }
285:
286: public function isNull(): TrinaryLogic
287: {
288: return TrinaryLogic::createNo();
289: }
290:
291: public function isConstantValue(): TrinaryLogic
292: {
293: return TrinaryLogic::createNo();
294: }
295:
296: public function isConstantScalarValue(): TrinaryLogic
297: {
298: return TrinaryLogic::createNo();
299: }
300:
301: public function getConstantScalarTypes(): array
302: {
303: return [];
304: }
305:
306: public function getConstantScalarValues(): array
307: {
308: return [];
309: }
310:
311: public function isTrue(): TrinaryLogic
312: {
313: return TrinaryLogic::createNo();
314: }
315:
316: public function isFalse(): TrinaryLogic
317: {
318: return TrinaryLogic::createNo();
319: }
320:
321: public function isBoolean(): TrinaryLogic
322: {
323: return TrinaryLogic::createNo();
324: }
325:
326: public function isFloat(): TrinaryLogic
327: {
328: return TrinaryLogic::createNo();
329: }
330:
331: public function isInteger(): TrinaryLogic
332: {
333: return TrinaryLogic::createNo();
334: }
335:
336: public function isString(): TrinaryLogic
337: {
338: return TrinaryLogic::createNo();
339: }
340:
341: public function isNumericString(): TrinaryLogic
342: {
343: return TrinaryLogic::createNo();
344: }
345:
346: public function isNonEmptyString(): TrinaryLogic
347: {
348: return TrinaryLogic::createNo();
349: }
350:
351: public function isNonFalsyString(): TrinaryLogic
352: {
353: return TrinaryLogic::createNo();
354: }
355:
356: public function isLiteralString(): TrinaryLogic
357: {
358: return TrinaryLogic::createNo();
359: }
360:
361: public function isClassStringType(): TrinaryLogic
362: {
363: return TrinaryLogic::createNo();
364: }
365:
366: public function getClassStringObjectType(): Type
367: {
368: return new ErrorType();
369: }
370:
371: public function getObjectTypeOrClassStringObjectType(): Type
372: {
373: return new ErrorType();
374: }
375:
376: public function isVoid(): TrinaryLogic
377: {
378: return TrinaryLogic::createNo();
379: }
380:
381: public function isScalar(): TrinaryLogic
382: {
383: return TrinaryLogic::createNo();
384: }
385:
386: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
387: {
388: return new BooleanType();
389: }
390:
391: public function isOffsetAccessible(): TrinaryLogic
392: {
393: return TrinaryLogic::createYes();
394: }
395:
396: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
397: {
398: $offsetType = $offsetType->toArrayKey();
399:
400: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
401: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
402: ) {
403: return TrinaryLogic::createNo();
404: }
405:
406: return TrinaryLogic::createMaybe();
407: }
408:
409: public function getOffsetValueType(Type $offsetType): Type
410: {
411: $offsetType = $offsetType->toArrayKey();
412: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
413: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
414: ) {
415: return new ErrorType();
416: }
417:
418: $type = $this->getItemType();
419: if ($type instanceof ErrorType) {
420: return new MixedType();
421: }
422:
423: return $type;
424: }
425:
426: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
427: {
428: if ($offsetType === null) {
429: $isKeyTypeInteger = $this->keyType->isInteger();
430: if ($isKeyTypeInteger->no()) {
431: $offsetType = new IntegerType();
432: } elseif ($isKeyTypeInteger->yes()) {
433: $offsetType = $this->keyType;
434: } else {
435: $integerTypes = [];
436: TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use (&$integerTypes): Type {
437: if ($type instanceof UnionType) {
438: return $traverse($type);
439: }
440:
441: $isInteger = $type->isInteger();
442: if ($isInteger->yes()) {
443: $integerTypes[] = $type;
444: }
445:
446: return $type;
447: });
448: if (count($integerTypes) === 0) {
449: $offsetType = $this->keyType;
450: } else {
451: $offsetType = TypeCombinator::union(...$integerTypes);
452: }
453: }
454: } else {
455: $offsetType = $offsetType->toArrayKey();
456: }
457:
458: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
459: if ($offsetType->isSuperTypeOf($this->keyType)->yes()) {
460: $builder = ConstantArrayTypeBuilder::createEmpty();
461: $builder->setOffsetValueType($offsetType, $valueType);
462: return $builder->getArray();
463: }
464:
465: return TypeCombinator::intersect(
466: new self(
467: TypeCombinator::union($this->keyType, $offsetType),
468: TypeCombinator::union($this->itemType, $valueType),
469: ),
470: new HasOffsetValueType($offsetType, $valueType),
471: new NonEmptyArrayType(),
472: );
473: }
474:
475: return TypeCombinator::intersect(
476: new self(
477: TypeCombinator::union($this->keyType, $offsetType),
478: $unionValues ? TypeCombinator::union($this->itemType, $valueType) : $valueType,
479: ),
480: new NonEmptyArrayType(),
481: );
482: }
483:
484: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
485: {
486: return new self(
487: $this->keyType,
488: TypeCombinator::union($this->itemType, $valueType),
489: );
490: }
491:
492: public function unsetOffset(Type $offsetType): Type
493: {
494: $offsetType = $offsetType->toArrayKey();
495:
496: if (
497: ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
498: && !$this->keyType->isSuperTypeOf($offsetType)->no()
499: ) {
500: $keyType = TypeCombinator::remove($this->keyType, $offsetType);
501: if ($keyType instanceof NeverType) {
502: return new ConstantArrayType([], []);
503: }
504:
505: return new self($keyType, $this->itemType);
506: }
507:
508: return $this;
509: }
510:
511: public function fillKeysArray(Type $valueType): Type
512: {
513: $itemType = $this->getItemType();
514: if ($itemType->isInteger()->no()) {
515: $stringKeyType = $itemType->toString();
516: if ($stringKeyType instanceof ErrorType) {
517: return $stringKeyType;
518: }
519:
520: return new ArrayType($stringKeyType, $valueType);
521: }
522:
523: return new ArrayType($itemType, $valueType);
524: }
525:
526: public function flipArray(): Type
527: {
528: return new self($this->getIterableValueType()->toArrayKey(), $this->getIterableKeyType());
529: }
530:
531: public function intersectKeyArray(Type $otherArraysType): Type
532: {
533: $isKeySuperType = $otherArraysType->getIterableKeyType()->isSuperTypeOf($this->getIterableKeyType());
534: if ($isKeySuperType->no()) {
535: return ConstantArrayTypeBuilder::createEmpty()->getArray();
536: }
537:
538: if ($isKeySuperType->yes()) {
539: return $otherArraysType->isIterableAtLeastOnce()->yes()
540: ? TypeCombinator::intersect($this, new NonEmptyArrayType())
541: : $this;
542: }
543:
544: return new self($otherArraysType->getIterableKeyType(), $this->getIterableValueType());
545: }
546:
547: public function popArray(): Type
548: {
549: return $this;
550: }
551:
552: public function searchArray(Type $needleType): Type
553: {
554: return TypeCombinator::union($this->getIterableKeyType(), new ConstantBooleanType(false));
555: }
556:
557: public function shiftArray(): Type
558: {
559: return $this;
560: }
561:
562: public function shuffleArray(): Type
563: {
564: return AccessoryArrayListType::intersectWith(new self(new IntegerType(), $this->itemType));
565: }
566:
567: public function isCallable(): TrinaryLogic
568: {
569: return TrinaryLogic::createMaybe()->and($this->itemType->isString());
570: }
571:
572: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
573: {
574: if ($this->isCallable()->no()) {
575: throw new ShouldNotHappenException();
576: }
577:
578: return [new TrivialParametersAcceptor()];
579: }
580:
581: public function toNumber(): Type
582: {
583: return new ErrorType();
584: }
585:
586: public function toString(): Type
587: {
588: return new ErrorType();
589: }
590:
591: public function toInteger(): Type
592: {
593: return TypeCombinator::union(
594: new ConstantIntegerType(0),
595: new ConstantIntegerType(1),
596: );
597: }
598:
599: public function toFloat(): Type
600: {
601: return TypeCombinator::union(
602: new ConstantFloatType(0.0),
603: new ConstantFloatType(1.0),
604: );
605: }
606:
607: public function toArray(): Type
608: {
609: return $this;
610: }
611:
612: public function toArrayKey(): Type
613: {
614: return new ErrorType();
615: }
616:
617: /** @deprecated Use getArraySize() instead */
618: public function count(): Type
619: {
620: return $this->getArraySize();
621: }
622:
623: /** @deprecated Use $offsetType->toArrayKey() instead */
624: public static function castToArrayKeyType(Type $offsetType): Type
625: {
626: return $offsetType->toArrayKey();
627: }
628:
629: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
630: {
631: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
632: return $receivedType->inferTemplateTypesOn($this);
633: }
634:
635: if ($receivedType->isArray()->yes()) {
636: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
637: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
638:
639: return $keyTypeMap->union($itemTypeMap);
640: }
641:
642: return TemplateTypeMap::createEmpty();
643: }
644:
645: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
646: {
647: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
648:
649: return array_merge(
650: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
651: $this->getItemType()->getReferencedTemplateTypes($variance),
652: );
653: }
654:
655: public function traverse(callable $cb): Type
656: {
657: $keyType = $cb($this->keyType);
658: $itemType = $cb($this->itemType);
659:
660: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
661: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
662: return new ConstantArrayType([], []);
663: }
664:
665: return new self($keyType, $itemType);
666: }
667:
668: return $this;
669: }
670:
671: public function toPhpDocNode(): TypeNode
672: {
673: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed';
674: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed';
675:
676: if ($isMixedKeyType) {
677: if ($isMixedItemType) {
678: return new IdentifierTypeNode('array');
679: }
680:
681: return new GenericTypeNode(
682: new IdentifierTypeNode('array'),
683: [
684: $this->itemType->toPhpDocNode(),
685: ],
686: );
687: }
688:
689: return new GenericTypeNode(
690: new IdentifierTypeNode('array'),
691: [
692: $this->keyType->toPhpDocNode(),
693: $this->itemType->toPhpDocNode(),
694: ],
695: );
696: }
697:
698: public function traverseSimultaneously(Type $right, callable $cb): Type
699: {
700: $keyType = $cb($this->keyType, $right->getIterableKeyType());
701: $itemType = $cb($this->itemType, $right->getIterableValueType());
702:
703: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
704: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
705: return new ConstantArrayType([], []);
706: }
707:
708: return new self($keyType, $itemType);
709: }
710:
711: return $this;
712: }
713:
714: public function tryRemove(Type $typeToRemove): ?Type
715: {
716: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
717: return TypeCombinator::intersect($this, new NonEmptyArrayType());
718: }
719:
720: if ($typeToRemove instanceof NonEmptyArrayType) {
721: return new ConstantArrayType([], []);
722: }
723:
724: if ($this->isConstantArray()->yes() && $typeToRemove instanceof HasOffsetType) {
725: return $this->unsetOffset($typeToRemove->getOffsetType());
726: }
727:
728: if ($this->isConstantArray()->yes() && $typeToRemove instanceof HasOffsetValueType) {
729: return $this->unsetOffset($typeToRemove->getOffsetType());
730: }
731:
732: return null;
733: }
734:
735: public function exponentiate(Type $exponent): Type
736: {
737: return new ErrorType();
738: }
739:
740: public function getFiniteTypes(): array
741: {
742: return [];
743: }
744:
745: /**
746: * @param mixed[] $properties
747: */
748: public static function __set_state(array $properties): Type
749: {
750: return new self(
751: $properties['keyType'],
752: $properties['itemType'],
753: );
754: }
755:
756: }
757: