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: if ($type->isInteger()->yes()) {
253: return new ConstantBooleanType(false);
254: }
255:
256: return new BooleanType();
257: }
258:
259: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
260: {
261: $offsetType = $offsetType->toArrayKey();
262:
263: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
264: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
265: ) {
266: return TrinaryLogic::createNo();
267: }
268:
269: return TrinaryLogic::createMaybe();
270: }
271:
272: public function getOffsetValueType(Type $offsetType): Type
273: {
274: $offsetType = $offsetType->toArrayKey();
275: if ($this->getKeyType()->isSuperTypeOf($offsetType)->no()
276: && ($offsetType->isString()->no() || !$offsetType->isConstantScalarValue()->no())
277: ) {
278: return new ErrorType();
279: }
280:
281: $type = $this->getItemType();
282: if ($type instanceof ErrorType) {
283: return new MixedType();
284: }
285:
286: return $type;
287: }
288:
289: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
290: {
291: if ($offsetType === null) {
292: $isKeyTypeInteger = $this->keyType->isInteger();
293: if ($isKeyTypeInteger->no()) {
294: $offsetType = new IntegerType();
295: } elseif ($isKeyTypeInteger->yes()) {
296: /** @var list<ConstantIntegerType> $constantScalars */
297: $constantScalars = $this->keyType->getConstantScalarTypes();
298: if (count($constantScalars) > 0) {
299: foreach ($constantScalars as $constantScalar) {
300: $constantScalars[] = ConstantTypeHelper::getTypeFromValue($constantScalar->getValue() + 1);
301: }
302:
303: $offsetType = TypeCombinator::union(...$constantScalars);
304: } else {
305: $offsetType = $this->keyType;
306: }
307: } else {
308: $integerTypes = [];
309: TypeTraverser::map($this->keyType, static function (Type $type, callable $traverse) use (&$integerTypes): Type {
310: if ($type instanceof UnionType) {
311: return $traverse($type);
312: }
313:
314: $isInteger = $type->isInteger();
315: if ($isInteger->yes()) {
316: $integerTypes[] = $type;
317: }
318:
319: return $type;
320: });
321: if (count($integerTypes) === 0) {
322: $offsetType = $this->keyType;
323: } else {
324: $offsetType = TypeCombinator::union(...$integerTypes);
325: }
326: }
327: } else {
328: $offsetType = $offsetType->toArrayKey();
329: }
330:
331: if ($offsetType instanceof ConstantStringType || $offsetType instanceof ConstantIntegerType) {
332: if ($offsetType->isSuperTypeOf($this->keyType)->yes()) {
333: $builder = ConstantArrayTypeBuilder::createEmpty();
334: $builder->setOffsetValueType($offsetType, $valueType);
335: return $builder->getArray();
336: }
337:
338: return TypeCombinator::intersect(
339: new self(
340: TypeCombinator::union($this->keyType, $offsetType),
341: TypeCombinator::union($this->itemType, $valueType),
342: ),
343: new HasOffsetValueType($offsetType, $valueType),
344: new NonEmptyArrayType(),
345: );
346: }
347:
348: return TypeCombinator::intersect(
349: new self(
350: TypeCombinator::union($this->keyType, $offsetType),
351: $unionValues ? TypeCombinator::union($this->itemType, $valueType) : $valueType,
352: ),
353: new NonEmptyArrayType(),
354: );
355: }
356:
357: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
358: {
359: return new self(
360: $this->keyType,
361: TypeCombinator::union($this->itemType, $valueType),
362: );
363: }
364:
365: public function unsetOffset(Type $offsetType): Type
366: {
367: $offsetType = $offsetType->toArrayKey();
368:
369: if (
370: ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
371: && !$this->keyType->isSuperTypeOf($offsetType)->no()
372: ) {
373: $keyType = TypeCombinator::remove($this->keyType, $offsetType);
374: if ($keyType instanceof NeverType) {
375: return new ConstantArrayType([], []);
376: }
377:
378: return new self($keyType, $this->itemType);
379: }
380:
381: return $this;
382: }
383:
384: public function fillKeysArray(Type $valueType): Type
385: {
386: $itemType = $this->getItemType();
387: if ($itemType->isInteger()->no()) {
388: $stringKeyType = $itemType->toString();
389: if ($stringKeyType instanceof ErrorType) {
390: return $stringKeyType;
391: }
392:
393: return new ArrayType($stringKeyType, $valueType);
394: }
395:
396: return new ArrayType($itemType, $valueType);
397: }
398:
399: public function flipArray(): Type
400: {
401: return new self($this->getIterableValueType()->toArrayKey(), $this->getIterableKeyType());
402: }
403:
404: public function intersectKeyArray(Type $otherArraysType): Type
405: {
406: $isKeySuperType = $otherArraysType->getIterableKeyType()->isSuperTypeOf($this->getIterableKeyType());
407: if ($isKeySuperType->no()) {
408: return ConstantArrayTypeBuilder::createEmpty()->getArray();
409: }
410:
411: if ($isKeySuperType->yes()) {
412: return $this;
413: }
414:
415: return new self($otherArraysType->getIterableKeyType(), $this->getIterableValueType());
416: }
417:
418: public function popArray(): Type
419: {
420: return $this;
421: }
422:
423: public function reverseArray(TrinaryLogic $preserveKeys): Type
424: {
425: return $this;
426: }
427:
428: public function searchArray(Type $needleType): Type
429: {
430: return TypeCombinator::union($this->getIterableKeyType(), new ConstantBooleanType(false));
431: }
432:
433: public function shiftArray(): Type
434: {
435: return $this;
436: }
437:
438: public function shuffleArray(): Type
439: {
440: return TypeCombinator::intersect(new self(new IntegerType(), $this->itemType), new AccessoryArrayListType());
441: }
442:
443: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
444: {
445: if ((new ConstantIntegerType(0))->isSuperTypeOf($lengthType)->yes()) {
446: return new ConstantArrayType([], []);
447: }
448:
449: if ($preserveKeys->no() && $this->keyType->isInteger()->yes()) {
450: return TypeCombinator::intersect(new self(new IntegerType(), $this->itemType), new AccessoryArrayListType());
451: }
452:
453: return $this;
454: }
455:
456: public function isCallable(): TrinaryLogic
457: {
458: return TrinaryLogic::createMaybe()->and($this->itemType->isString());
459: }
460:
461: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
462: {
463: if ($this->isCallable()->no()) {
464: throw new ShouldNotHappenException();
465: }
466:
467: return [new TrivialParametersAcceptor()];
468: }
469:
470: public function toInteger(): Type
471: {
472: return TypeCombinator::union(
473: new ConstantIntegerType(0),
474: new ConstantIntegerType(1),
475: );
476: }
477:
478: public function toFloat(): Type
479: {
480: return TypeCombinator::union(
481: new ConstantFloatType(0.0),
482: new ConstantFloatType(1.0),
483: );
484: }
485:
486: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
487: {
488: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
489: return $receivedType->inferTemplateTypesOn($this);
490: }
491:
492: if ($receivedType->isArray()->yes()) {
493: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
494: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
495:
496: return $keyTypeMap->union($itemTypeMap);
497: }
498:
499: return TemplateTypeMap::createEmpty();
500: }
501:
502: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
503: {
504: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
505:
506: return array_merge(
507: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
508: $this->getItemType()->getReferencedTemplateTypes($variance),
509: );
510: }
511:
512: public function traverse(callable $cb): Type
513: {
514: $keyType = $cb($this->keyType);
515: $itemType = $cb($this->itemType);
516:
517: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
518: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
519: return new ConstantArrayType([], []);
520: }
521:
522: return new self($keyType, $itemType);
523: }
524:
525: return $this;
526: }
527:
528: public function toPhpDocNode(): TypeNode
529: {
530: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
531: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
532:
533: if ($isMixedKeyType) {
534: if ($isMixedItemType) {
535: return new IdentifierTypeNode('array');
536: }
537:
538: return new GenericTypeNode(
539: new IdentifierTypeNode('array'),
540: [
541: $this->itemType->toPhpDocNode(),
542: ],
543: );
544: }
545:
546: return new GenericTypeNode(
547: new IdentifierTypeNode('array'),
548: [
549: $this->keyType->toPhpDocNode(),
550: $this->itemType->toPhpDocNode(),
551: ],
552: );
553: }
554:
555: public function traverseSimultaneously(Type $right, callable $cb): Type
556: {
557: $keyType = $cb($this->keyType, $right->getIterableKeyType());
558: $itemType = $cb($this->itemType, $right->getIterableValueType());
559:
560: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
561: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
562: return new ConstantArrayType([], []);
563: }
564:
565: return new self($keyType, $itemType);
566: }
567:
568: return $this;
569: }
570:
571: public function tryRemove(Type $typeToRemove): ?Type
572: {
573: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
574: return TypeCombinator::intersect($this, new NonEmptyArrayType());
575: }
576:
577: if ($typeToRemove instanceof NonEmptyArrayType) {
578: return new ConstantArrayType([], []);
579: }
580:
581: return null;
582: }
583:
584: public function getFiniteTypes(): array
585: {
586: return [];
587: }
588:
589: }
590: