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 isOffsetAccessLegal(): TrinaryLogic
397: {
398: return TrinaryLogic::createYes();
399: }
400:
401: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
402: {
403: $offsetType = $offsetType->toArrayKey();
404:
405: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
406: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
407: ) {
408: return TrinaryLogic::createNo();
409: }
410:
411: return TrinaryLogic::createMaybe();
412: }
413:
414: public function getOffsetValueType(Type $offsetType): Type
415: {
416: $offsetType = $offsetType->toArrayKey();
417: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
418: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
419: ) {
420: return new ErrorType();
421: }
422:
423: $type = $this->getItemType();
424: if ($type instanceof ErrorType) {
425: return new MixedType();
426: }
427:
428: return $type;
429: }
430:
431: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
432: {
433: if ($offsetType === null) {
434: $isKeyTypeInteger = $this->keyType->isInteger();
435: if ($isKeyTypeInteger->no()) {
436: $offsetType = new IntegerType();
437: } elseif ($isKeyTypeInteger->yes()) {
438: $offsetType = $this->keyType;
439: } else {
440: $integerTypes = [];
441: TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use (&$integerTypes): Type {
442: if ($type instanceof UnionType) {
443: return $traverse($type);
444: }
445:
446: $isInteger = $type->isInteger();
447: if ($isInteger->yes()) {
448: $integerTypes[] = $type;
449: }
450:
451: return $type;
452: });
453: if (count($integerTypes) === 0) {
454: $offsetType = $this->keyType;
455: } else {
456: $offsetType = TypeCombinator::union(...$integerTypes);
457: }
458: }
459: } else {
460: $offsetType = $offsetType->toArrayKey();
461: }
462:
463: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
464: if ($offsetType->isSuperTypeOf($this->keyType)->yes()) {
465: $builder = ConstantArrayTypeBuilder::createEmpty();
466: $builder->setOffsetValueType($offsetType, $valueType);
467: return $builder->getArray();
468: }
469:
470: return TypeCombinator::intersect(
471: new self(
472: TypeCombinator::union($this->keyType, $offsetType),
473: TypeCombinator::union($this->itemType, $valueType),
474: ),
475: new HasOffsetValueType($offsetType, $valueType),
476: new NonEmptyArrayType(),
477: );
478: }
479:
480: return TypeCombinator::intersect(
481: new self(
482: TypeCombinator::union($this->keyType, $offsetType),
483: $unionValues ? TypeCombinator::union($this->itemType, $valueType) : $valueType,
484: ),
485: new NonEmptyArrayType(),
486: );
487: }
488:
489: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
490: {
491: return new self(
492: $this->keyType,
493: TypeCombinator::union($this->itemType, $valueType),
494: );
495: }
496:
497: public function unsetOffset(Type $offsetType): Type
498: {
499: $offsetType = $offsetType->toArrayKey();
500:
501: if (
502: ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
503: && !$this->keyType->isSuperTypeOf($offsetType)->no()
504: ) {
505: $keyType = TypeCombinator::remove($this->keyType, $offsetType);
506: if ($keyType instanceof NeverType) {
507: return new ConstantArrayType([], []);
508: }
509:
510: return new self($keyType, $this->itemType);
511: }
512:
513: return $this;
514: }
515:
516: public function fillKeysArray(Type $valueType): Type
517: {
518: $itemType = $this->getItemType();
519: if ($itemType->isInteger()->no()) {
520: $stringKeyType = $itemType->toString();
521: if ($stringKeyType instanceof ErrorType) {
522: return $stringKeyType;
523: }
524:
525: return new ArrayType($stringKeyType, $valueType);
526: }
527:
528: return new ArrayType($itemType, $valueType);
529: }
530:
531: public function flipArray(): Type
532: {
533: return new self($this->getIterableValueType()->toArrayKey(), $this->getIterableKeyType());
534: }
535:
536: public function intersectKeyArray(Type $otherArraysType): Type
537: {
538: $isKeySuperType = $otherArraysType->getIterableKeyType()->isSuperTypeOf($this->getIterableKeyType());
539: if ($isKeySuperType->no()) {
540: return ConstantArrayTypeBuilder::createEmpty()->getArray();
541: }
542:
543: if ($isKeySuperType->yes()) {
544: return $this;
545: }
546:
547: return new self($otherArraysType->getIterableKeyType(), $this->getIterableValueType());
548: }
549:
550: public function popArray(): Type
551: {
552: return $this;
553: }
554:
555: public function searchArray(Type $needleType): Type
556: {
557: return TypeCombinator::union($this->getIterableKeyType(), new ConstantBooleanType(false));
558: }
559:
560: public function shiftArray(): Type
561: {
562: return $this;
563: }
564:
565: public function shuffleArray(): Type
566: {
567: return AccessoryArrayListType::intersectWith(new self(new IntegerType(), $this->itemType));
568: }
569:
570: public function isCallable(): TrinaryLogic
571: {
572: return TrinaryLogic::createMaybe()->and($this->itemType->isString());
573: }
574:
575: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
576: {
577: if ($this->isCallable()->no()) {
578: throw new ShouldNotHappenException();
579: }
580:
581: return [new TrivialParametersAcceptor()];
582: }
583:
584: public function toNumber(): Type
585: {
586: return new ErrorType();
587: }
588:
589: public function toAbsoluteNumber(): Type
590: {
591: return new ErrorType();
592: }
593:
594: public function toString(): Type
595: {
596: return new ErrorType();
597: }
598:
599: public function toInteger(): Type
600: {
601: return TypeCombinator::union(
602: new ConstantIntegerType(0),
603: new ConstantIntegerType(1),
604: );
605: }
606:
607: public function toFloat(): Type
608: {
609: return TypeCombinator::union(
610: new ConstantFloatType(0.0),
611: new ConstantFloatType(1.0),
612: );
613: }
614:
615: public function toArray(): Type
616: {
617: return $this;
618: }
619:
620: public function toArrayKey(): Type
621: {
622: return new ErrorType();
623: }
624:
625: /** @deprecated Use getArraySize() instead */
626: public function count(): Type
627: {
628: return $this->getArraySize();
629: }
630:
631: /** @deprecated Use $offsetType->toArrayKey() instead */
632: public static function castToArrayKeyType(Type $offsetType): Type
633: {
634: return $offsetType->toArrayKey();
635: }
636:
637: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
638: {
639: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
640: return $receivedType->inferTemplateTypesOn($this);
641: }
642:
643: if ($receivedType->isArray()->yes()) {
644: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
645: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
646:
647: return $keyTypeMap->union($itemTypeMap);
648: }
649:
650: return TemplateTypeMap::createEmpty();
651: }
652:
653: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
654: {
655: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
656:
657: return array_merge(
658: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
659: $this->getItemType()->getReferencedTemplateTypes($variance),
660: );
661: }
662:
663: public function traverse(callable $cb): Type
664: {
665: $keyType = $cb($this->keyType);
666: $itemType = $cb($this->itemType);
667:
668: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
669: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
670: return new ConstantArrayType([], []);
671: }
672:
673: return new self($keyType, $itemType);
674: }
675:
676: return $this;
677: }
678:
679: public function toPhpDocNode(): TypeNode
680: {
681: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed';
682: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed';
683:
684: if ($isMixedKeyType) {
685: if ($isMixedItemType) {
686: return new IdentifierTypeNode('array');
687: }
688:
689: return new GenericTypeNode(
690: new IdentifierTypeNode('array'),
691: [
692: $this->itemType->toPhpDocNode(),
693: ],
694: );
695: }
696:
697: return new GenericTypeNode(
698: new IdentifierTypeNode('array'),
699: [
700: $this->keyType->toPhpDocNode(),
701: $this->itemType->toPhpDocNode(),
702: ],
703: );
704: }
705:
706: public function traverseSimultaneously(Type $right, callable $cb): Type
707: {
708: $keyType = $cb($this->keyType, $right->getIterableKeyType());
709: $itemType = $cb($this->itemType, $right->getIterableValueType());
710:
711: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
712: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
713: return new ConstantArrayType([], []);
714: }
715:
716: return new self($keyType, $itemType);
717: }
718:
719: return $this;
720: }
721:
722: public function tryRemove(Type $typeToRemove): ?Type
723: {
724: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
725: return TypeCombinator::intersect($this, new NonEmptyArrayType());
726: }
727:
728: if ($typeToRemove instanceof NonEmptyArrayType) {
729: return new ConstantArrayType([], []);
730: }
731:
732: if ($this->isConstantArray()->yes() && $typeToRemove instanceof HasOffsetType) {
733: return $this->unsetOffset($typeToRemove->getOffsetType());
734: }
735:
736: if ($this->isConstantArray()->yes() && $typeToRemove instanceof HasOffsetValueType) {
737: return $this->unsetOffset($typeToRemove->getOffsetType());
738: }
739:
740: return null;
741: }
742:
743: public function exponentiate(Type $exponent): Type
744: {
745: return new ErrorType();
746: }
747:
748: public function getFiniteTypes(): array
749: {
750: return [];
751: }
752:
753: /**
754: * @param mixed[] $properties
755: */
756: public static function __set_state(array $properties): Type
757: {
758: return new self(
759: $properties['keyType'],
760: $properties['itemType'],
761: );
762: }
763:
764: }
765: