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