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: return $this;
446: }
447:
448: public function isCallable(): TrinaryLogic
449: {
450: return TrinaryLogic::createMaybe()->and($this->itemType->isString());
451: }
452:
453: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
454: {
455: if ($this->isCallable()->no()) {
456: throw new ShouldNotHappenException();
457: }
458:
459: return [new TrivialParametersAcceptor()];
460: }
461:
462: public function toInteger(): Type
463: {
464: return TypeCombinator::union(
465: new ConstantIntegerType(0),
466: new ConstantIntegerType(1),
467: );
468: }
469:
470: public function toFloat(): Type
471: {
472: return TypeCombinator::union(
473: new ConstantFloatType(0.0),
474: new ConstantFloatType(1.0),
475: );
476: }
477:
478: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
479: {
480: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
481: return $receivedType->inferTemplateTypesOn($this);
482: }
483:
484: if ($receivedType->isArray()->yes()) {
485: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
486: $itemTypeMap = $this->getItemType()->inferTemplateTypes($receivedType->getIterableValueType());
487:
488: return $keyTypeMap->union($itemTypeMap);
489: }
490:
491: return TemplateTypeMap::createEmpty();
492: }
493:
494: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
495: {
496: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
497:
498: return array_merge(
499: $this->getIterableKeyType()->getReferencedTemplateTypes($variance),
500: $this->getItemType()->getReferencedTemplateTypes($variance),
501: );
502: }
503:
504: public function traverse(callable $cb): Type
505: {
506: $keyType = $cb($this->keyType);
507: $itemType = $cb($this->itemType);
508:
509: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
510: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
511: return new ConstantArrayType([], []);
512: }
513:
514: return new self($keyType, $itemType);
515: }
516:
517: return $this;
518: }
519:
520: public function toPhpDocNode(): TypeNode
521: {
522: $isMixedKeyType = $this->keyType instanceof MixedType && $this->keyType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->keyType->isExplicitMixed();
523: $isMixedItemType = $this->itemType instanceof MixedType && $this->itemType->describe(VerbosityLevel::precise()) === 'mixed' && !$this->itemType->isExplicitMixed();
524:
525: if ($isMixedKeyType) {
526: if ($isMixedItemType) {
527: return new IdentifierTypeNode('array');
528: }
529:
530: return new GenericTypeNode(
531: new IdentifierTypeNode('array'),
532: [
533: $this->itemType->toPhpDocNode(),
534: ],
535: );
536: }
537:
538: return new GenericTypeNode(
539: new IdentifierTypeNode('array'),
540: [
541: $this->keyType->toPhpDocNode(),
542: $this->itemType->toPhpDocNode(),
543: ],
544: );
545: }
546:
547: public function traverseSimultaneously(Type $right, callable $cb): Type
548: {
549: $keyType = $cb($this->keyType, $right->getIterableKeyType());
550: $itemType = $cb($this->itemType, $right->getIterableValueType());
551:
552: if ($keyType !== $this->keyType || $itemType !== $this->itemType) {
553: if ($keyType instanceof NeverType && $itemType instanceof NeverType) {
554: return new ConstantArrayType([], []);
555: }
556:
557: return new self($keyType, $itemType);
558: }
559:
560: return $this;
561: }
562:
563: public function tryRemove(Type $typeToRemove): ?Type
564: {
565: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
566: return TypeCombinator::intersect($this, new NonEmptyArrayType());
567: }
568:
569: if ($typeToRemove instanceof NonEmptyArrayType) {
570: return new ConstantArrayType([], []);
571: }
572:
573: return null;
574: }
575:
576: public function getFiniteTypes(): array
577: {
578: return [];
579: }
580:
581: }
582: