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\HasOffsetValueType;
15: use PHPStan\Type\Accessory\NonEmptyArrayType;
16: use PHPStan\Type\Constant\ConstantArrayType;
17: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
18: use PHPStan\Type\Constant\ConstantBooleanType;
19: use PHPStan\Type\Constant\ConstantFloatType;
20: use PHPStan\Type\Constant\ConstantIntegerType;
21: use PHPStan\Type\Constant\ConstantStringType;
22: use PHPStan\Type\Generic\TemplateMixedType;
23: use PHPStan\Type\Generic\TemplateStrictMixedType;
24: use PHPStan\Type\Generic\TemplateTypeMap;
25: use PHPStan\Type\Generic\TemplateTypeVariance;
26: use PHPStan\Type\Traits\ArrayTypeTrait;
27: use PHPStan\Type\Traits\MaybeCallableTypeTrait;
28: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
29: use PHPStan\Type\Traits\NonObjectTypeTrait;
30: use PHPStan\Type\Traits\UndecidedBooleanTypeTrait;
31: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
32: use function array_merge;
33: use function count;
34: use function sprintf;
35:
36: /** @api */
37: class ArrayType implements Type
38: {
39:
40: use ArrayTypeTrait;
41: use MaybeCallableTypeTrait;
42: use NonObjectTypeTrait;
43: use UndecidedBooleanTypeTrait;
44: use UndecidedComparisonTypeTrait;
45: use NonGeneralizableTypeTrait;
46:
47: private Type $keyType;
48:
49: /** @api */
50: public function __construct(Type $keyType, private Type $itemType)
51: {
52: if ($keyType->describe(VerbosityLevel::value()) === '(int|string)') {
53: $keyType = new MixedType();
54: }
55: if ($keyType instanceof StrictMixedType && !$keyType instanceof TemplateStrictMixedType) {
56: $keyType = new UnionType([new StringType(), new IntegerType()]);
57: }
58:
59: $this->keyType = $keyType;
60: }
61:
62: public function getKeyType(): Type
63: {
64: return $this->keyType;
65: }
66:
67: public function getItemType(): Type
68: {
69: return $this->itemType;
70: }
71:
72: public function getReferencedClasses(): array
73: {
74: return array_merge(
75: $this->keyType->getReferencedClasses(),
76: $this->getItemType()->getReferencedClasses(),
77: );
78: }
79:
80: public function getConstantArrays(): array
81: {
82: return [];
83: }
84:
85: public function accepts(Type $type, bool $strictTypes): AcceptsResult
86: {
87: if ($type instanceof CompoundType) {
88: return $type->isAcceptedBy($this, $strictTypes);
89: }
90:
91: if ($type instanceof ConstantArrayType) {
92: $result = AcceptsResult::createYes();
93: $thisKeyType = $this->keyType;
94: $itemType = $this->getItemType();
95: foreach ($type->getKeyTypes() as $i => $keyType) {
96: $valueType = $type->getValueTypes()[$i];
97: $acceptsKey = $thisKeyType->accepts($keyType, $strictTypes);
98: $acceptsValue = $itemType->accepts($valueType, $strictTypes);
99: $result = $result->and($acceptsKey)->and($acceptsValue);
100: }
101:
102: return $result;
103: }
104:
105: if ($type instanceof ArrayType) {
106: return $this->getItemType()->accepts($type->getItemType(), $strictTypes)
107: ->and($this->keyType->accepts($type->keyType, $strictTypes));
108: }
109:
110: return AcceptsResult::createNo();
111: }
112:
113: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
114: {
115: if ($type instanceof self || $type instanceof ConstantArrayType) {
116: return $this->getItemType()->isSuperTypeOf($type->getItemType())
117: ->and($this->getIterableKeyType()->isSuperTypeOf($type->getIterableKeyType()));
118: }
119:
120: if ($type instanceof CompoundType) {
121: return $type->isSubTypeOf($this);
122: }
123:
124: return IsSuperTypeOfResult::createNo();
125: }
126:
127: public function equals(Type $type): bool
128: {
129: return $type instanceof self
130: && $this->getItemType()->equals($type->getIterableValueType())
131: && $this->keyType->equals($type->keyType);
132: }
133:
134: public function describe(VerbosityLevel $level): string
135: {
136: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
137: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
138:
139: $valueHandler = function () use ($level, $isMixedKeyType, $isMixedItemType): string {
140: if ($isMixedKeyType || $this->keyType instanceof NeverType) {
141: if ($isMixedItemType || $this->itemType instanceof NeverType) {
142: return 'array';
143: }
144:
145: return sprintf('array<%s>', $this->itemType->describe($level));
146: }
147:
148: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
149: };
150:
151: return $level->handle(
152: $valueHandler,
153: $valueHandler,
154: function () use ($level, $isMixedKeyType, $isMixedItemType): string {
155: if ($isMixedKeyType) {
156: if ($isMixedItemType) {
157: return 'array';
158: }
159:
160: return sprintf('array<%s>', $this->itemType->describe($level));
161: }
162:
163: return sprintf('array<%s, %s>', $this->keyType->describe($level), $this->itemType->describe($level));
164: },
165: );
166: }
167:
168: public function generalizeValues(): self
169: {
170: return new self($this->keyType, $this->itemType->generalize(GeneralizePrecision::lessSpecific()));
171: }
172:
173: public function getKeysArray(): Type
174: {
175: return TypeCombinator::intersect(new self(new IntegerType(), $this->getIterableKeyType()), new AccessoryArrayListType());
176: }
177:
178: public function getValuesArray(): Type
179: {
180: return TypeCombinator::intersect(new self(new IntegerType(), $this->itemType), new AccessoryArrayListType());
181: }
182:
183: public function isIterableAtLeastOnce(): TrinaryLogic
184: {
185: return TrinaryLogic::createMaybe();
186: }
187:
188: public function getArraySize(): Type
189: {
190: return IntegerRangeType::fromInterval(0, null);
191: }
192:
193: public function getIterableKeyType(): Type
194: {
195: $keyType = $this->keyType;
196: if ($keyType instanceof MixedType && !$keyType instanceof TemplateMixedType) {
197: return new BenevolentUnionType([new IntegerType(), new StringType()]);
198: }
199: if ($keyType instanceof StrictMixedType) {
200: return new BenevolentUnionType([new IntegerType(), new StringType()]);
201: }
202:
203: return $keyType;
204: }
205:
206: public function getFirstIterableKeyType(): Type
207: {
208: return $this->getIterableKeyType();
209: }
210:
211: public function getLastIterableKeyType(): Type
212: {
213: return $this->getIterableKeyType();
214: }
215:
216: public function getIterableValueType(): Type
217: {
218: return $this->getItemType();
219: }
220:
221: public function getFirstIterableValueType(): Type
222: {
223: return $this->getItemType();
224: }
225:
226: public function getLastIterableValueType(): Type
227: {
228: return $this->getItemType();
229: }
230:
231: public function isConstantArray(): TrinaryLogic
232: {
233: return TrinaryLogic::createNo();
234: }
235:
236: public function isList(): TrinaryLogic
237: {
238: if (IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($this->getKeyType())->no()) {
239: return TrinaryLogic::createNo();
240: }
241:
242: return TrinaryLogic::createMaybe();
243: }
244:
245: public function isConstantValue(): TrinaryLogic
246: {
247: return TrinaryLogic::createNo();
248: }
249:
250: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
251: {
252: return new BooleanType();
253: }
254:
255: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
256: {
257: $offsetType = $offsetType->toArrayKey();
258:
259: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
260: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
261: ) {
262: return TrinaryLogic::createNo();
263: }
264:
265: return TrinaryLogic::createMaybe();
266: }
267:
268: public function getOffsetValueType(Type $offsetType): Type
269: {
270: $offsetType = $offsetType->toArrayKey();
271: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
272: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
273: ) {
274: return new ErrorType();
275: }
276:
277: $type = $this->getItemType();
278: if ($type instanceof ErrorType) {
279: return new MixedType();
280: }
281:
282: return $type;
283: }
284:
285: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
286: {
287: if ($offsetType === null) {
288: $isKeyTypeInteger = $this->keyType->isInteger();
289: if ($isKeyTypeInteger->no()) {
290: $offsetType = new IntegerType();
291: } elseif ($isKeyTypeInteger->yes()) {
292: $offsetType = $this->keyType;
293: } else {
294: $integerTypes = [];
295: TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use (&$integerTypes): Type {
296: if ($type instanceof UnionType) {
297: return $traverse($type);
298: }
299:
300: $isInteger = $type->isInteger();
301: if ($isInteger->yes()) {
302: $integerTypes[] = $type;
303: }
304:
305: return $type;
306: });
307: if (count($integerTypes) === 0) {
308: $offsetType = $this->keyType;
309: } else {
310: $offsetType = TypeCombinator::union(...$integerTypes);
311: }
312: }
313: } else {
314: $offsetType = $offsetType->toArrayKey();
315: }
316:
317: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
318: if ($offsetType->isSuperTypeOf($this->keyType)->yes()) {
319: $builder = ConstantArrayTypeBuilder::createEmpty();
320: $builder->setOffsetValueType($offsetType, $valueType);
321: return $builder->getArray();
322: }
323:
324: return TypeCombinator::intersect(
325: new self(
326: TypeCombinator::union($this->keyType, $offsetType),
327: TypeCombinator::union($this->itemType, $valueType),
328: ),
329: new HasOffsetValueType($offsetType, $valueType),
330: new NonEmptyArrayType(),
331: );
332: }
333:
334: return TypeCombinator::intersect(
335: new self(
336: TypeCombinator::union($this->keyType, $offsetType),
337: $unionValues ? TypeCombinator::union($this->itemType, $valueType) : $valueType,
338: ),
339: new NonEmptyArrayType(),
340: );
341: }
342:
343: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
344: {
345: return new self(
346: $this->keyType,
347: TypeCombinator::union($this->itemType, $valueType),
348: );
349: }
350:
351: public function unsetOffset(Type $offsetType): Type
352: {
353: $offsetType = $offsetType->toArrayKey();
354:
355: if (
356: ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
357: && !$this->keyType->isSuperTypeOf($offsetType)->no()
358: ) {
359: $keyType = TypeCombinator::remove($this->keyType, $offsetType);
360: if ($keyType instanceof NeverType) {
361: return new ConstantArrayType([], []);
362: }
363:
364: return new self($keyType, $this->itemType);
365: }
366:
367: return $this;
368: }
369:
370: public function fillKeysArray(Type $valueType): Type
371: {
372: $itemType = $this->getItemType();
373: if ($itemType->isInteger()->no()) {
374: $stringKeyType = $itemType->toString();
375: if ($stringKeyType instanceof ErrorType) {
376: return $stringKeyType;
377: }
378:
379: return new ArrayType($stringKeyType, $valueType);
380: }
381:
382: return new ArrayType($itemType, $valueType);
383: }
384:
385: public function flipArray(): Type
386: {
387: return new self($this->getIterableValueType()->toArrayKey(), $this->getIterableKeyType());
388: }
389:
390: public function intersectKeyArray(Type $otherArraysType): Type
391: {
392: $isKeySuperType = $otherArraysType->getIterableKeyType()->isSuperTypeOf($this->getIterableKeyType());
393: if ($isKeySuperType->no()) {
394: return ConstantArrayTypeBuilder::createEmpty()->getArray();
395: }
396:
397: if ($isKeySuperType->yes()) {
398: return $this;
399: }
400:
401: return new self($otherArraysType->getIterableKeyType(), $this->getIterableValueType());
402: }
403:
404: public function popArray(): Type
405: {
406: return $this;
407: }
408:
409: public function reverseArray(TrinaryLogic $preserveKeys): Type
410: {
411: return $this;
412: }
413:
414: public function searchArray(Type $needleType): Type
415: {
416: return TypeCombinator::union($this->getIterableKeyType(), new ConstantBooleanType(false));
417: }
418:
419: public function shiftArray(): Type
420: {
421: return $this;
422: }
423:
424: public function shuffleArray(): Type
425: {
426: return TypeCombinator::intersect(new self(new IntegerType(), $this->itemType), new AccessoryArrayListType());
427: }
428:
429: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
430: {
431: return $this;
432: }
433:
434: public function isCallable(): TrinaryLogic
435: {
436: return TrinaryLogic::createMaybe()->and($this->itemType->isString());
437: }
438:
439: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
440: {
441: if ($this->isCallable()->no()) {
442: throw new ShouldNotHappenException();
443: }
444:
445: return [new TrivialParametersAcceptor()];
446: }
447:
448: public function toInteger(): Type
449: {
450: return TypeCombinator::union(
451: new ConstantIntegerType(0),
452: new ConstantIntegerType(1),
453: );
454: }
455:
456: public function toFloat(): Type
457: {
458: return TypeCombinator::union(
459: new ConstantFloatType(0.0),
460: new ConstantFloatType(1.0),
461: );
462: }
463:
464: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
465: {
466: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
467: return $receivedType->inferTemplateTypesOn($this);
468: }
469:
470: if ($receivedType->isArray()->yes()) {
471: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
472: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
473:
474: return $keyTypeMap->union($itemTypeMap);
475: }
476:
477: return TemplateTypeMap::createEmpty();
478: }
479:
480: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
481: {
482: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
483:
484: return array_merge(
485: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
486: $this->getItemType()->getReferencedTemplateTypes($variance),
487: );
488: }
489:
490: public function traverse(callable $cb): Type
491: {
492: $keyType = $cb($this->keyType);
493: $itemType = $cb($this->itemType);
494:
495: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
496: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
497: return new ConstantArrayType([], []);
498: }
499:
500: return new self($keyType, $itemType);
501: }
502:
503: return $this;
504: }
505:
506: public function toPhpDocNode(): TypeNode
507: {
508: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
509: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
510:
511: if ($isMixedKeyType) {
512: if ($isMixedItemType) {
513: return new IdentifierTypeNode('array');
514: }
515:
516: return new GenericTypeNode(
517: new IdentifierTypeNode('array'),
518: [
519: $this->itemType->toPhpDocNode(),
520: ],
521: );
522: }
523:
524: return new GenericTypeNode(
525: new IdentifierTypeNode('array'),
526: [
527: $this->keyType->toPhpDocNode(),
528: $this->itemType->toPhpDocNode(),
529: ],
530: );
531: }
532:
533: public function traverseSimultaneously(Type $right, callable $cb): Type
534: {
535: $keyType = $cb($this->keyType, $right->getIterableKeyType());
536: $itemType = $cb($this->itemType, $right->getIterableValueType());
537:
538: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
539: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
540: return new ConstantArrayType([], []);
541: }
542:
543: return new self($keyType, $itemType);
544: }
545:
546: return $this;
547: }
548:
549: public function tryRemove(Type $typeToRemove): ?Type
550: {
551: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
552: return TypeCombinator::intersect($this, new NonEmptyArrayType());
553: }
554:
555: if ($typeToRemove instanceof NonEmptyArrayType) {
556: return new ConstantArrayType([], []);
557: }
558:
559: return null;
560: }
561:
562: public function getFiniteTypes(): array
563: {
564: return [];
565: }
566:
567: }
568: