1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Constant;
4:
5: use Nette\Utils\Strings;
6: use PHPStan\Analyser\OutOfClassScope;
7: use PHPStan\DependencyInjection\BleedingEdgeToggle;
8: use PHPStan\Internal\CombinationsHelper;
9: use PHPStan\Php\PhpVersion;
10: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
11: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
12: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
13: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
14: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
15: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
16: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
17: use PHPStan\Reflection\ClassMemberAccessAnswerer;
18: use PHPStan\Reflection\InaccessibleMethod;
19: use PHPStan\Reflection\InitializerExprTypeResolver;
20: use PHPStan\Reflection\ParametersAcceptor;
21: use PHPStan\Reflection\PhpVersionStaticAccessor;
22: use PHPStan\Reflection\TrivialParametersAcceptor;
23: use PHPStan\ShouldNotHappenException;
24: use PHPStan\TrinaryLogic;
25: use PHPStan\Type\AcceptsResult;
26: use PHPStan\Type\Accessory\AccessoryArrayListType;
27: use PHPStan\Type\Accessory\HasOffsetValueType;
28: use PHPStan\Type\Accessory\NonEmptyArrayType;
29: use PHPStan\Type\ArrayType;
30: use PHPStan\Type\BooleanType;
31: use PHPStan\Type\CompoundType;
32: use PHPStan\Type\ConstantScalarType;
33: use PHPStan\Type\ConstantType;
34: use PHPStan\Type\ErrorType;
35: use PHPStan\Type\GeneralizePrecision;
36: use PHPStan\Type\Generic\TemplateMixedType;
37: use PHPStan\Type\Generic\TemplateTypeMap;
38: use PHPStan\Type\Generic\TemplateTypeVariance;
39: use PHPStan\Type\IntegerRangeType;
40: use PHPStan\Type\IntersectionType;
41: use PHPStan\Type\MixedType;
42: use PHPStan\Type\NeverType;
43: use PHPStan\Type\Type;
44: use PHPStan\Type\TypeCombinator;
45: use PHPStan\Type\UnionType;
46: use PHPStan\Type\VerbosityLevel;
47: use function array_keys;
48: use function array_map;
49: use function array_merge;
50: use function array_pop;
51: use function array_push;
52: use function array_reverse;
53: use function array_slice;
54: use function array_unique;
55: use function array_values;
56: use function assert;
57: use function count;
58: use function implode;
59: use function in_array;
60: use function is_bool;
61: use function is_int;
62: use function is_string;
63: use function min;
64: use function pow;
65: use function range;
66: use function sort;
67: use function sprintf;
68: use function str_contains;
69:
70: /**
71: * @api
72: */
73: class ConstantArrayType extends ArrayType implements ConstantType
74: {
75:
76: private const DESCRIBE_LIMIT = 8;
77:
78: private TrinaryLogic $isList;
79:
80: /** @var self[]|null */
81: private ?array $allArrays = null;
82:
83: /** @var non-empty-list<int> */
84: private array $nextAutoIndexes;
85:
86: /**
87: * @api
88: * @param array<int, ConstantIntegerType|ConstantStringType> $keyTypes
89: * @param array<int, Type> $valueTypes
90: * @param non-empty-list<int>|int $nextAutoIndexes
91: * @param int[] $optionalKeys
92: */
93: public function __construct(
94: private array $keyTypes,
95: private array $valueTypes,
96: int|array $nextAutoIndexes = [0],
97: private array $optionalKeys = [],
98: bool|TrinaryLogic $isList = false,
99: )
100: {
101: assert(count($keyTypes) === count($valueTypes));
102:
103: if (is_int($nextAutoIndexes)) {
104: $nextAutoIndexes = [$nextAutoIndexes];
105: }
106:
107: $this->nextAutoIndexes = $nextAutoIndexes;
108:
109: $keyTypesCount = count($this->keyTypes);
110: if ($keyTypesCount === 0) {
111: $keyType = new NeverType(true);
112: $isList = TrinaryLogic::createYes();
113: } elseif ($keyTypesCount === 1) {
114: $keyType = $this->keyTypes[0];
115: } else {
116: $keyType = new UnionType($this->keyTypes);
117: }
118:
119: if (is_bool($isList)) {
120: $isList = TrinaryLogic::createFromBoolean($isList);
121: }
122: $this->isList = $isList;
123:
124: parent::__construct(
125: $keyType,
126: count($valueTypes) > 0 ? TypeCombinator::union(...$valueTypes) : new NeverType(true),
127: );
128: }
129:
130: public function getConstantArrays(): array
131: {
132: return [$this];
133: }
134:
135: public function isConstantValue(): TrinaryLogic
136: {
137: return TrinaryLogic::createYes();
138: }
139:
140: /** @deprecated Use isIterableAtLeastOnce()->no() instead */
141: public function isEmpty(): bool
142: {
143: return count($this->keyTypes) === 0;
144: }
145:
146: /**
147: * @return non-empty-list<int>
148: */
149: public function getNextAutoIndexes(): array
150: {
151: return $this->nextAutoIndexes;
152: }
153:
154: /**
155: * @deprecated
156: */
157: public function getNextAutoIndex(): int
158: {
159: return $this->nextAutoIndexes[count($this->nextAutoIndexes) - 1];
160: }
161:
162: /**
163: * @return int[]
164: */
165: public function getOptionalKeys(): array
166: {
167: return $this->optionalKeys;
168: }
169:
170: /**
171: * @return self[]
172: */
173: public function getAllArrays(): array
174: {
175: if ($this->allArrays !== null) {
176: return $this->allArrays;
177: }
178:
179: if (count($this->optionalKeys) <= 10) {
180: $optionalKeysCombinations = $this->powerSet($this->optionalKeys);
181: } else {
182: $optionalKeysCombinations = [
183: [],
184: $this->optionalKeys,
185: ];
186: }
187:
188: $requiredKeys = [];
189: foreach (array_keys($this->keyTypes) as $i) {
190: if (in_array($i, $this->optionalKeys, true)) {
191: continue;
192: }
193: $requiredKeys[] = $i;
194: }
195:
196: $arrays = [];
197: foreach ($optionalKeysCombinations as $combination) {
198: $keys = array_merge($requiredKeys, $combination);
199: sort($keys);
200:
201: if ($this->isList->yes() && array_keys($keys) !== $keys) {
202: continue;
203: }
204:
205: $builder = ConstantArrayTypeBuilder::createEmpty();
206: foreach ($keys as $i) {
207: $builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i]);
208: }
209:
210: $array = $builder->getArray();
211: if (!$array instanceof ConstantArrayType) {
212: throw new ShouldNotHappenException();
213: }
214:
215: $arrays[] = $array;
216: }
217:
218: return $this->allArrays = $arrays;
219: }
220:
221: /**
222: * @template T
223: * @param T[] $in
224: * @return T[][]
225: */
226: private function powerSet(array $in): array
227: {
228: $count = count($in);
229: $members = pow(2, $count);
230: $return = [];
231: for ($i = 0; $i < $members; $i++) {
232: $b = sprintf('%0' . $count . 'b', $i);
233: $out = [];
234: for ($j = 0; $j < $count; $j++) {
235: if ($b[$j] !== '1') {
236: continue;
237: }
238:
239: $out[] = $in[$j];
240: }
241: $return[] = $out;
242: }
243:
244: return $return;
245: }
246:
247: /**
248: * @return array<int, ConstantIntegerType|ConstantStringType>
249: */
250: public function getKeyTypes(): array
251: {
252: return $this->keyTypes;
253: }
254:
255: /** @deprecated Use getFirstIterableKeyType() instead */
256: public function getFirstKeyType(): Type
257: {
258: return $this->getFirstIterableKeyType();
259: }
260:
261: /** @deprecated Use getLastIterableKeyType() instead */
262: public function getLastKeyType(): Type
263: {
264: return $this->getLastIterableKeyType();
265: }
266:
267: /**
268: * @return array<int, Type>
269: */
270: public function getValueTypes(): array
271: {
272: return $this->valueTypes;
273: }
274:
275: /** @deprecated Use getFirstIterableValueType() instead */
276: public function getFirstValueType(): Type
277: {
278: return $this->getFirstIterableValueType();
279: }
280:
281: /** @deprecated Use getLastIterableValueType() instead */
282: public function getLastValueType(): Type
283: {
284: return $this->getLastIterableValueType();
285: }
286:
287: public function isOptionalKey(int $i): bool
288: {
289: return in_array($i, $this->optionalKeys, true);
290: }
291:
292: public function accepts(Type $type, bool $strictTypes): TrinaryLogic
293: {
294: return $this->acceptsWithReason($type, $strictTypes)->result;
295: }
296:
297: public function acceptsWithReason(Type $type, bool $strictTypes): AcceptsResult
298: {
299: if ($type instanceof MixedType && !$type instanceof TemplateMixedType) {
300: return $type->isAcceptedWithReasonBy($this, $strictTypes);
301: }
302:
303: if ($type instanceof self && count($this->keyTypes) === 0) {
304: return AcceptsResult::createFromBoolean(count($type->keyTypes) === 0);
305: }
306:
307: $result = AcceptsResult::createYes();
308: foreach ($this->keyTypes as $i => $keyType) {
309: $valueType = $this->valueTypes[$i];
310: $hasOffsetValueType = $type->hasOffsetValueType($keyType);
311: $hasOffset = new AcceptsResult(
312: $hasOffsetValueType,
313: $hasOffsetValueType->yes() || !$type->isConstantArray()->yes() ? [] : [sprintf('Array %s have offset %s.', $hasOffsetValueType->no() ? 'does not' : 'might not', $keyType->describe(VerbosityLevel::value()))],
314: );
315: if ($hasOffset->no()) {
316: if ($this->isOptionalKey($i)) {
317: continue;
318: }
319: return $hasOffset;
320: }
321: if ($hasOffset->maybe() && $this->isOptionalKey($i)) {
322: $hasOffset = AcceptsResult::createYes();
323: }
324:
325: $result = $result->and($hasOffset);
326: $otherValueType = $type->getOffsetValueType($keyType);
327: $verbosity = VerbosityLevel::getRecommendedLevelByType($valueType, $otherValueType);
328: $acceptsValue = $valueType->acceptsWithReason($otherValueType, $strictTypes)->decorateReasons(
329: static fn (string $reason) => sprintf(
330: 'Offset %s (%s) does not accept type %s: %s',
331: $keyType->describe(VerbosityLevel::value()),
332: $valueType->describe($verbosity),
333: $otherValueType->describe($verbosity),
334: $reason,
335: ),
336: );
337: if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0 && $type->isConstantArray()->yes()) {
338: $acceptsValue = new AcceptsResult($acceptsValue->result, [
339: sprintf(
340: 'Offset %s (%s) does not accept type %s.',
341: $keyType->describe(VerbosityLevel::value()),
342: $valueType->describe($verbosity),
343: $otherValueType->describe($verbosity),
344: ),
345: ]);
346: }
347: if ($acceptsValue->no()) {
348: return $acceptsValue;
349: }
350: $result = $result->and($acceptsValue);
351: }
352:
353: $result = $result->and(new AcceptsResult($type->isArray(), []));
354: if ($type->isOversizedArray()->yes()) {
355: if (!$result->no()) {
356: return AcceptsResult::createYes();
357: }
358: }
359:
360: return $result;
361: }
362:
363: public function isSuperTypeOf(Type $type): TrinaryLogic
364: {
365: if ($type instanceof self) {
366: if (count($this->keyTypes) === 0) {
367: if (count($type->keyTypes) > 0) {
368: if (count($type->optionalKeys) > 0) {
369: return TrinaryLogic::createMaybe();
370: }
371: return TrinaryLogic::createNo();
372: }
373:
374: return TrinaryLogic::createYes();
375: }
376:
377: $results = [];
378: foreach ($this->keyTypes as $i => $keyType) {
379: $hasOffset = $type->hasOffsetValueType($keyType);
380: if ($hasOffset->no()) {
381: if (!$this->isOptionalKey($i)) {
382: return TrinaryLogic::createNo();
383: }
384:
385: $results[] = TrinaryLogic::createYes();
386: continue;
387: } elseif ($hasOffset->maybe() && !$this->isOptionalKey($i)) {
388: $results[] = TrinaryLogic::createMaybe();
389: }
390:
391: $isValueSuperType = $this->valueTypes[$i]->isSuperTypeOf($type->getOffsetValueType($keyType));
392: if ($isValueSuperType->no()) {
393: return TrinaryLogic::createNo();
394: }
395: $results[] = $isValueSuperType;
396: }
397:
398: return TrinaryLogic::createYes()->and(...$results);
399: }
400:
401: if ($type instanceof ArrayType) {
402: $result = TrinaryLogic::createMaybe();
403: if (count($this->keyTypes) === 0) {
404: return $result;
405: }
406:
407: $isKeySuperType = $this->getKeyType()->isSuperTypeOf($type->getKeyType());
408: if ($isKeySuperType->no()) {
409: return TrinaryLogic::createNo();
410: }
411:
412: return $result->and($isKeySuperType, $this->getItemType()->isSuperTypeOf($type->getItemType()));
413: }
414:
415: if ($type instanceof CompoundType) {
416: return $type->isSubTypeOf($this);
417: }
418:
419: return TrinaryLogic::createNo();
420: }
421:
422: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
423: {
424: if ($this->isIterableAtLeastOnce()->no() && count($type->getConstantScalarValues()) === 1) {
425: // @phpstan-ignore equal.invalid, equal.notAllowed
426: return new ConstantBooleanType($type->getConstantScalarValues()[0] == []); // phpcs:ignore
427: }
428:
429: return new BooleanType();
430: }
431:
432: public function equals(Type $type): bool
433: {
434: if (!$type instanceof self) {
435: return false;
436: }
437:
438: if (count($this->keyTypes) !== count($type->keyTypes)) {
439: return false;
440: }
441:
442: foreach ($this->keyTypes as $i => $keyType) {
443: $valueType = $this->valueTypes[$i];
444: if (!$valueType->equals($type->valueTypes[$i])) {
445: return false;
446: }
447: if (!$keyType->equals($type->keyTypes[$i])) {
448: return false;
449: }
450: }
451:
452: if ($this->optionalKeys !== $type->optionalKeys) {
453: return false;
454: }
455:
456: return true;
457: }
458:
459: public function isCallable(): TrinaryLogic
460: {
461: $typeAndMethods = $this->findTypeAndMethodNames();
462: if ($typeAndMethods === []) {
463: return TrinaryLogic::createNo();
464: }
465:
466: $results = array_map(
467: static fn (ConstantArrayTypeAndMethod $typeAndMethod): TrinaryLogic => $typeAndMethod->getCertainty(),
468: $typeAndMethods,
469: );
470:
471: return TrinaryLogic::createYes()->and(...$results);
472: }
473:
474: /**
475: * @return ParametersAcceptor[]
476: */
477: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
478: {
479: $typeAndMethodNames = $this->findTypeAndMethodNames();
480: if ($typeAndMethodNames === []) {
481: throw new ShouldNotHappenException();
482: }
483:
484: $acceptors = [];
485: foreach ($typeAndMethodNames as $typeAndMethodName) {
486: if ($typeAndMethodName->isUnknown() || !$typeAndMethodName->getCertainty()->yes()) {
487: $acceptors[] = new TrivialParametersAcceptor();
488: continue;
489: }
490:
491: $method = $typeAndMethodName->getType()
492: ->getMethod($typeAndMethodName->getMethod(), $scope);
493:
494: if (!$scope->canCallMethod($method)) {
495: $acceptors[] = new InaccessibleMethod($method);
496: continue;
497: }
498:
499: array_push($acceptors, ...$method->getVariants());
500: }
501:
502: return $acceptors;
503: }
504:
505: /**
506: * @return array{Type, Type}|array{}
507: */
508: private function getClassOrObjectAndMethods(): array
509: {
510: if (count($this->keyTypes) !== 2) {
511: return [];
512: }
513:
514: $classOrObject = null;
515: $method = null;
516: foreach ($this->keyTypes as $i => $keyType) {
517: if ($keyType->isSuperTypeOf(new ConstantIntegerType(0))->yes()) {
518: $classOrObject = $this->valueTypes[$i];
519: continue;
520: }
521:
522: if (!$keyType->isSuperTypeOf(new ConstantIntegerType(1))->yes()) {
523: continue;
524: }
525:
526: $method = $this->valueTypes[$i];
527: }
528:
529: if ($classOrObject === null || $method === null) {
530: return [];
531: }
532:
533: return [$classOrObject, $method];
534: }
535:
536: /** @deprecated Use findTypeAndMethodNames() instead */
537: public function findTypeAndMethodName(): ?ConstantArrayTypeAndMethod
538: {
539: $callableArray = $this->getClassOrObjectAndMethods();
540: if ($callableArray === []) {
541: return null;
542: }
543:
544: [$classOrObject, $method] = $callableArray;
545: if (!$method instanceof ConstantStringType) {
546: return ConstantArrayTypeAndMethod::createUnknown();
547: }
548:
549: $type = $classOrObject->getObjectTypeOrClassStringObjectType();
550: if (!$type->isObject()->yes()) {
551: return ConstantArrayTypeAndMethod::createUnknown();
552: }
553:
554: $has = $type->hasMethod($method->getValue());
555: if (!$has->no()) {
556: if ($this->isOptionalKey(0) || $this->isOptionalKey(1)) {
557: $has = $has->and(TrinaryLogic::createMaybe());
558: }
559:
560: return ConstantArrayTypeAndMethod::createConcrete($type, $method->getValue(), $has);
561: }
562:
563: return null;
564: }
565:
566: /** @return ConstantArrayTypeAndMethod[] */
567: public function findTypeAndMethodNames(): array
568: {
569: $callableArray = $this->getClassOrObjectAndMethods();
570: if ($callableArray === []) {
571: return [];
572: }
573:
574: [$classOrObject, $methods] = $callableArray;
575: if (count($methods->getConstantStrings()) === 0) {
576: return [ConstantArrayTypeAndMethod::createUnknown()];
577: }
578:
579: $type = $classOrObject->getObjectTypeOrClassStringObjectType();
580: if (!$type->isObject()->yes()) {
581: return [ConstantArrayTypeAndMethod::createUnknown()];
582: }
583:
584: $typeAndMethods = [];
585: $phpVersion = PhpVersionStaticAccessor::getInstance();
586: foreach ($methods->getConstantStrings() as $method) {
587: $has = $type->hasMethod($method->getValue());
588: if ($has->no()) {
589: continue;
590: }
591:
592: if (
593: BleedingEdgeToggle::isBleedingEdge()
594: && $has->yes()
595: && !$phpVersion->supportsCallableInstanceMethods()
596: ) {
597: $methodReflection = $type->getMethod($method->getValue(), new OutOfClassScope());
598: if ($classOrObject->isString()->yes() && !$methodReflection->isStatic()) {
599: continue;
600: }
601: }
602:
603: if ($this->isOptionalKey(0) || $this->isOptionalKey(1)) {
604: $has = $has->and(TrinaryLogic::createMaybe());
605: }
606:
607: $typeAndMethods[] = ConstantArrayTypeAndMethod::createConcrete($type, $method->getValue(), $has);
608: }
609:
610: return $typeAndMethods;
611: }
612:
613: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
614: {
615: $offsetType = $offsetType->toArrayKey();
616:
617: $result = TrinaryLogic::createNo();
618: foreach ($this->keyTypes as $i => $keyType) {
619: if (
620: $keyType instanceof ConstantIntegerType
621: && !$offsetType->isString()->no()
622: && $offsetType->isConstantScalarValue()->no()
623: ) {
624: return TrinaryLogic::createMaybe();
625: }
626:
627: $has = $keyType->isSuperTypeOf($offsetType);
628: if ($has->yes()) {
629: if ($this->isOptionalKey($i)) {
630: return TrinaryLogic::createMaybe();
631: }
632: return TrinaryLogic::createYes();
633: }
634: if (!$has->maybe()) {
635: continue;
636: }
637:
638: $result = TrinaryLogic::createMaybe();
639: }
640:
641: return $result;
642: }
643:
644: public function getOffsetValueType(Type $offsetType): Type
645: {
646: $offsetType = $offsetType->toArrayKey();
647: $matchingValueTypes = [];
648: $all = true;
649: foreach ($this->keyTypes as $i => $keyType) {
650: if ($keyType->isSuperTypeOf($offsetType)->no()) {
651: $all = false;
652: continue;
653: }
654:
655: $matchingValueTypes[] = $this->valueTypes[$i];
656: }
657:
658: if ($all) {
659: if (count($this->keyTypes) === 0) {
660: return new ErrorType();
661: }
662:
663: return $this->getIterableValueType();
664: }
665:
666: if (count($matchingValueTypes) > 0) {
667: $type = TypeCombinator::union(...$matchingValueTypes);
668: if ($type instanceof ErrorType) {
669: return new MixedType();
670: }
671:
672: return $type;
673: }
674:
675: return new ErrorType(); // undefined offset
676: }
677:
678: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
679: {
680: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
681: $builder->setOffsetValueType($offsetType, $valueType);
682:
683: return $builder->getArray();
684: }
685:
686: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
687: {
688: $offsetType = $offsetType->toArrayKey();
689: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
690: foreach ($this->keyTypes as $keyType) {
691: if ($offsetType->isSuperTypeOf($keyType)->no()) {
692: continue;
693: }
694:
695: $builder->setOffsetValueType($keyType, $valueType);
696: }
697:
698: return $builder->getArray();
699: }
700:
701: public function unsetOffset(Type $offsetType): Type
702: {
703: $offsetType = $offsetType->toArrayKey();
704: if ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType) {
705: foreach ($this->keyTypes as $i => $keyType) {
706: if ($keyType->getValue() !== $offsetType->getValue()) {
707: continue;
708: }
709:
710: $keyTypes = $this->keyTypes;
711: unset($keyTypes[$i]);
712: $valueTypes = $this->valueTypes;
713: unset($valueTypes[$i]);
714:
715: $newKeyTypes = [];
716: $newValueTypes = [];
717: $newOptionalKeys = [];
718:
719: $k = 0;
720: foreach ($keyTypes as $j => $newKeyType) {
721: $newKeyTypes[] = $newKeyType;
722: $newValueTypes[] = $valueTypes[$j];
723: if (in_array($j, $this->optionalKeys, true)) {
724: $newOptionalKeys[] = $k;
725: }
726: $k++;
727: }
728:
729: return new self($newKeyTypes, $newValueTypes, $this->nextAutoIndexes, $newOptionalKeys, TrinaryLogic::createNo());
730: }
731:
732: return $this;
733: }
734:
735: $constantScalars = $offsetType->getConstantScalarTypes();
736: if (count($constantScalars) > 0) {
737: $optionalKeys = $this->optionalKeys;
738:
739: foreach ($constantScalars as $constantScalar) {
740: $constantScalar = $constantScalar->toArrayKey();
741: if (!$constantScalar instanceof ConstantIntegerType && !$constantScalar instanceof ConstantStringType) {
742: continue;
743: }
744:
745: foreach ($this->keyTypes as $i => $keyType) {
746: if ($keyType->getValue() !== $constantScalar->getValue()) {
747: continue;
748: }
749:
750: if (in_array($i, $optionalKeys, true)) {
751: continue 2;
752: }
753:
754: $optionalKeys[] = $i;
755: }
756: }
757:
758: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, TrinaryLogic::createNo());
759: }
760:
761: $optionalKeys = $this->optionalKeys;
762: $isList = $this->isList;
763: foreach ($this->keyTypes as $i => $keyType) {
764: if (!$offsetType->isSuperTypeOf($keyType)->yes()) {
765: continue;
766: }
767: $optionalKeys[] = $i;
768: $isList = TrinaryLogic::createNo();
769: }
770: $optionalKeys = array_values(array_unique($optionalKeys));
771:
772: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, $isList);
773: }
774:
775: public function fillKeysArray(Type $valueType): Type
776: {
777: $builder = ConstantArrayTypeBuilder::createEmpty();
778:
779: foreach ($this->valueTypes as $i => $keyType) {
780: if ($keyType->isInteger()->no()) {
781: $stringKeyType = $keyType->toString();
782: if ($stringKeyType instanceof ErrorType) {
783: return $stringKeyType;
784: }
785:
786: $builder->setOffsetValueType($stringKeyType, $valueType, $this->isOptionalKey($i));
787: } else {
788: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i));
789: }
790: }
791:
792: return $builder->getArray();
793: }
794:
795: public function flipArray(): Type
796: {
797: $builder = ConstantArrayTypeBuilder::createEmpty();
798:
799: foreach ($this->keyTypes as $i => $keyType) {
800: $valueType = $this->valueTypes[$i];
801: $builder->setOffsetValueType(
802: $valueType->toArrayKey(),
803: $keyType,
804: $this->isOptionalKey($i),
805: );
806: }
807:
808: return $builder->getArray();
809: }
810:
811: public function intersectKeyArray(Type $otherArraysType): Type
812: {
813: $builder = ConstantArrayTypeBuilder::createEmpty();
814:
815: foreach ($this->keyTypes as $i => $keyType) {
816: $valueType = $this->valueTypes[$i];
817: $has = $otherArraysType->hasOffsetValueType($keyType);
818: if ($has->no()) {
819: continue;
820: }
821: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i) || !$has->yes());
822: }
823:
824: return $builder->getArray();
825: }
826:
827: public function popArray(): Type
828: {
829: return $this->removeLastElements(1);
830: }
831:
832: public function searchArray(Type $needleType): Type
833: {
834: $matches = [];
835: $hasIdenticalValue = false;
836:
837: foreach ($this->valueTypes as $index => $valueType) {
838: $isNeedleSuperType = $valueType->isSuperTypeOf($needleType);
839: if ($isNeedleSuperType->no()) {
840: continue;
841: }
842:
843: if ($needleType instanceof ConstantScalarType && $valueType instanceof ConstantScalarType
844: && $needleType->getValue() === $valueType->getValue()
845: && !$this->isOptionalKey($index)
846: ) {
847: $hasIdenticalValue = true;
848: }
849:
850: $matches[] = $this->keyTypes[$index];
851: }
852:
853: if (count($matches) > 0) {
854: if ($hasIdenticalValue) {
855: return TypeCombinator::union(...$matches);
856: }
857:
858: return TypeCombinator::union(new ConstantBooleanType(false), ...$matches);
859: }
860:
861: return new ConstantBooleanType(false);
862: }
863:
864: public function shiftArray(): Type
865: {
866: return $this->removeFirstElements(1);
867: }
868:
869: public function shuffleArray(): Type
870: {
871: $valuesArray = $this->getValuesArray();
872:
873: $isIterableAtLeastOnce = $valuesArray->isIterableAtLeastOnce();
874: if ($isIterableAtLeastOnce->no()) {
875: return $valuesArray;
876: }
877:
878: $generalizedArray = new ArrayType($valuesArray->getKeyType(), $valuesArray->getItemType());
879:
880: if ($isIterableAtLeastOnce->yes()) {
881: $generalizedArray = TypeCombinator::intersect($generalizedArray, new NonEmptyArrayType());
882: }
883: if ($valuesArray->isList->yes()) {
884: $generalizedArray = AccessoryArrayListType::intersectWith($generalizedArray);
885: }
886:
887: return $generalizedArray;
888: }
889:
890: public function isIterableAtLeastOnce(): TrinaryLogic
891: {
892: $keysCount = count($this->keyTypes);
893: if ($keysCount === 0) {
894: return TrinaryLogic::createNo();
895: }
896:
897: $optionalKeysCount = count($this->optionalKeys);
898: if ($optionalKeysCount < $keysCount) {
899: return TrinaryLogic::createYes();
900: }
901:
902: return TrinaryLogic::createMaybe();
903: }
904:
905: public function getArraySize(): Type
906: {
907: $optionalKeysCount = count($this->optionalKeys);
908: $totalKeysCount = count($this->getKeyTypes());
909: if ($optionalKeysCount === 0) {
910: return new ConstantIntegerType($totalKeysCount);
911: }
912:
913: return IntegerRangeType::fromInterval($totalKeysCount - $optionalKeysCount, $totalKeysCount);
914: }
915:
916: public function getFirstIterableKeyType(): Type
917: {
918: $keyTypes = [];
919: foreach ($this->keyTypes as $i => $keyType) {
920: $keyTypes[] = $keyType;
921: if (!$this->isOptionalKey($i)) {
922: break;
923: }
924: }
925:
926: return TypeCombinator::union(...$keyTypes);
927: }
928:
929: public function getLastIterableKeyType(): Type
930: {
931: $keyTypes = [];
932: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
933: $keyTypes[] = $this->keyTypes[$i];
934: if (!$this->isOptionalKey($i)) {
935: break;
936: }
937: }
938:
939: return TypeCombinator::union(...$keyTypes);
940: }
941:
942: public function getFirstIterableValueType(): Type
943: {
944: $valueTypes = [];
945: foreach ($this->valueTypes as $i => $valueType) {
946: $valueTypes[] = $valueType;
947: if (!$this->isOptionalKey($i)) {
948: break;
949: }
950: }
951:
952: return TypeCombinator::union(...$valueTypes);
953: }
954:
955: public function getLastIterableValueType(): Type
956: {
957: $valueTypes = [];
958: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
959: $valueTypes[] = $this->valueTypes[$i];
960: if (!$this->isOptionalKey($i)) {
961: break;
962: }
963: }
964:
965: return TypeCombinator::union(...$valueTypes);
966: }
967:
968: public function isConstantArray(): TrinaryLogic
969: {
970: return TrinaryLogic::createYes();
971: }
972:
973: public function isList(): TrinaryLogic
974: {
975: return $this->isList;
976: }
977:
978: /** @deprecated Use popArray() instead */
979: public function removeLast(): self
980: {
981: return $this->removeLastElements(1);
982: }
983:
984: /** @param positive-int $length */
985: private function removeLastElements(int $length): self
986: {
987: $keyTypesCount = count($this->keyTypes);
988: if ($keyTypesCount === 0) {
989: return $this;
990: }
991:
992: $keyTypes = $this->keyTypes;
993: $valueTypes = $this->valueTypes;
994: $optionalKeys = $this->optionalKeys;
995: $nextAutoindex = $this->nextAutoIndexes;
996:
997: $optionalKeysRemoved = 0;
998: $newLength = $keyTypesCount - $length;
999: for ($i = $keyTypesCount - 1; $i >= 0; $i--) {
1000: $isOptional = $this->isOptionalKey($i);
1001:
1002: if ($i >= $newLength) {
1003: if ($isOptional) {
1004: $optionalKeysRemoved++;
1005: foreach ($optionalKeys as $key => $value) {
1006: if ($value === $i) {
1007: unset($optionalKeys[$key]);
1008: break;
1009: }
1010: }
1011: }
1012:
1013: $removedKeyType = array_pop($keyTypes);
1014: array_pop($valueTypes);
1015: $nextAutoindex = $removedKeyType instanceof ConstantIntegerType
1016: ? $removedKeyType->getValue()
1017: : $this->getNextAutoIndex(); // @phpstan-ignore method.deprecated
1018: continue;
1019: }
1020:
1021: if ($isOptional || $optionalKeysRemoved <= 0) {
1022: continue;
1023: }
1024:
1025: $optionalKeys[] = $i;
1026: $optionalKeysRemoved--;
1027: }
1028:
1029: return new self(
1030: $keyTypes,
1031: $valueTypes,
1032: $nextAutoindex,
1033: array_values($optionalKeys),
1034: $this->isList,
1035: );
1036: }
1037:
1038: /** @deprecated Use shiftArray() instead */
1039: public function removeFirst(): self
1040: {
1041: return $this->removeFirstElements(1);
1042: }
1043:
1044: /** @param positive-int $length */
1045: private function removeFirstElements(int $length, bool $reindex = true): self
1046: {
1047: $builder = ConstantArrayTypeBuilder::createEmpty();
1048:
1049: $optionalKeysIgnored = 0;
1050: foreach ($this->keyTypes as $i => $keyType) {
1051: $isOptional = $this->isOptionalKey($i);
1052: if ($i <= $length - 1) {
1053: if ($isOptional) {
1054: $optionalKeysIgnored++;
1055: }
1056: continue;
1057: }
1058:
1059: if (!$isOptional && $optionalKeysIgnored > 0) {
1060: $isOptional = true;
1061: $optionalKeysIgnored--;
1062: }
1063:
1064: $valueType = $this->valueTypes[$i];
1065: if ($reindex && $keyType instanceof ConstantIntegerType) {
1066: $keyType = null;
1067: }
1068:
1069: $builder->setOffsetValueType($keyType, $valueType, $isOptional);
1070: }
1071:
1072: $array = $builder->getArray();
1073: if (!$array instanceof self) {
1074: throw new ShouldNotHappenException();
1075: }
1076:
1077: return $array;
1078: }
1079:
1080: public function slice(int $offset, ?int $limit, bool $preserveKeys = false): self
1081: {
1082: $keyTypesCount = count($this->keyTypes);
1083: if ($keyTypesCount === 0) {
1084: return $this;
1085: }
1086:
1087: $limit ??= $keyTypesCount;
1088: if ($limit < 0) {
1089: // Negative limits prevent access to the most right n elements
1090: return $this->removeLastElements($limit * -1)
1091: ->slice($offset, null, $preserveKeys);
1092: }
1093:
1094: if ($keyTypesCount + $offset <= 0) {
1095: // A negative offset cannot reach left outside the array
1096: $offset = 0;
1097: }
1098:
1099: if ($offset < 0) {
1100: /*
1101: * Transforms the problem with the negative offset in one with a positive offset using array reversion.
1102: * The reason is belows handling of optional keys which works only from left to right.
1103: *
1104: * e.g.
1105: * array{a: 0, b: 1, c: 2, d: 3, e: 4}
1106: * with offset -4 and limit 2 (which would be sliced to array{b: 1, c: 2})
1107: *
1108: * is transformed via reversion to
1109: *
1110: * array{e: 4, d: 3, c: 2, b: 1, a: 0}
1111: * with offset 2 and limit 2 (which will be sliced to array{c: 2, b: 1} and then reversed again)
1112: */
1113: $offset *= -1;
1114: $reversedLimit = min($limit, $offset);
1115: $reversedOffset = $offset - $reversedLimit;
1116: return $this->reverse(true)
1117: ->slice($reversedOffset, $reversedLimit, $preserveKeys)
1118: ->reverse(true);
1119: }
1120:
1121: if ($offset > 0) {
1122: return $this->removeFirstElements($offset, false)
1123: ->slice(0, $limit, $preserveKeys);
1124: }
1125:
1126: $builder = ConstantArrayTypeBuilder::createEmpty();
1127:
1128: $nonOptionalElementsCount = 0;
1129: $hasOptional = false;
1130: for ($i = 0; $nonOptionalElementsCount < $limit && $i < $keyTypesCount; $i++) {
1131: $isOptional = $this->isOptionalKey($i);
1132: if (!$isOptional) {
1133: $nonOptionalElementsCount++;
1134: } else {
1135: $hasOptional = true;
1136: }
1137:
1138: $isLastElement = $nonOptionalElementsCount >= $limit || $i + 1 >= $keyTypesCount;
1139: if ($isLastElement && $limit < $keyTypesCount && $hasOptional) {
1140: // If the slice is not full yet, but has at least one optional key
1141: // the last non-optional element is going to be optional.
1142: // Otherwise, it would not fit into the slice if previous non-optional keys are there.
1143: $isOptional = true;
1144: }
1145:
1146: $builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i], $isOptional);
1147: }
1148:
1149: $slice = $builder->getArray();
1150: if (!$slice instanceof self) {
1151: throw new ShouldNotHappenException();
1152: }
1153:
1154: return $preserveKeys ? $slice : $slice->reindex();
1155: }
1156:
1157: public function reverse(bool $preserveKeys = false): self
1158: {
1159: $keyTypesReversed = array_reverse($this->keyTypes, true);
1160: $keyTypes = array_values($keyTypesReversed);
1161: $keyTypesReversedKeys = array_keys($keyTypesReversed);
1162: $optionalKeys = array_map(static fn (int $optionalKey): int => $keyTypesReversedKeys[$optionalKey], $this->optionalKeys);
1163:
1164: $reversed = new self($keyTypes, array_reverse($this->valueTypes), $this->nextAutoIndexes, $optionalKeys, TrinaryLogic::createNo());
1165:
1166: return $preserveKeys ? $reversed : $reversed->reindex();
1167: }
1168:
1169: /** @param positive-int $length */
1170: public function chunk(int $length, bool $preserveKeys = false): self
1171: {
1172: $builder = ConstantArrayTypeBuilder::createEmpty();
1173:
1174: $keyTypesCount = count($this->keyTypes);
1175: for ($i = 0; $i < $keyTypesCount; $i += $length) {
1176: $chunk = $this->slice($i, $length, true);
1177: $builder->setOffsetValueType(null, $preserveKeys ? $chunk : $chunk->getValuesArray());
1178: }
1179:
1180: $chunks = $builder->getArray();
1181: if (!$chunks instanceof self) {
1182: throw new ShouldNotHappenException();
1183: }
1184:
1185: return $chunks;
1186: }
1187:
1188: private function reindex(): self
1189: {
1190: $keyTypes = [];
1191: $autoIndex = 0;
1192:
1193: foreach ($this->keyTypes as $keyType) {
1194: if (!$keyType instanceof ConstantIntegerType) {
1195: $keyTypes[] = $keyType;
1196: continue;
1197: }
1198:
1199: $keyTypes[] = new ConstantIntegerType($autoIndex);
1200: $autoIndex++;
1201: }
1202:
1203: return new self($keyTypes, $this->valueTypes, [$autoIndex], $this->optionalKeys, TrinaryLogic::createYes());
1204: }
1205:
1206: public function toBoolean(): BooleanType
1207: {
1208: return $this->getArraySize()->toBoolean();
1209: }
1210:
1211: public function toInteger(): Type
1212: {
1213: return $this->toBoolean()->toInteger();
1214: }
1215:
1216: public function toFloat(): Type
1217: {
1218: return $this->toBoolean()->toFloat();
1219: }
1220:
1221: public function generalize(GeneralizePrecision $precision): Type
1222: {
1223: if (count($this->keyTypes) === 0) {
1224: return $this;
1225: }
1226:
1227: if ($precision->isTemplateArgument()) {
1228: return $this->traverse(static fn (Type $type) => $type->generalize($precision));
1229: }
1230:
1231: $arrayType = new ArrayType(
1232: $this->getKeyType()->generalize($precision),
1233: $this->getItemType()->generalize($precision),
1234: );
1235:
1236: $keyTypesCount = count($this->keyTypes);
1237: $optionalKeysCount = count($this->optionalKeys);
1238:
1239: $accessoryTypes = [];
1240: if ($precision->isMoreSpecific() && ($keyTypesCount - $optionalKeysCount) < 32) {
1241: foreach ($this->keyTypes as $i => $keyType) {
1242: if ($this->isOptionalKey($i)) {
1243: continue;
1244: }
1245:
1246: $accessoryTypes[] = new HasOffsetValueType($keyType, $this->valueTypes[$i]->generalize($precision));
1247: }
1248: } elseif ($keyTypesCount > $optionalKeysCount) {
1249: $accessoryTypes[] = new NonEmptyArrayType();
1250: }
1251:
1252: if ($this->isList()->yes()) {
1253: $arrayType = AccessoryArrayListType::intersectWith($arrayType);
1254: }
1255:
1256: if (count($accessoryTypes) > 0) {
1257: return TypeCombinator::intersect($arrayType, ...$accessoryTypes);
1258: }
1259:
1260: return $arrayType;
1261: }
1262:
1263: /**
1264: * @return self
1265: */
1266: public function generalizeValues(): ArrayType
1267: {
1268: $valueTypes = [];
1269: foreach ($this->valueTypes as $valueType) {
1270: $valueTypes[] = $valueType->generalize(GeneralizePrecision::lessSpecific());
1271: }
1272:
1273: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1274: }
1275:
1276: /** @deprecated */
1277: public function generalizeToArray(): Type
1278: {
1279: $isIterableAtLeastOnce = $this->isIterableAtLeastOnce();
1280: if ($isIterableAtLeastOnce->no()) {
1281: return $this;
1282: }
1283:
1284: $arrayType = new ArrayType($this->getKeyType(), $this->getItemType());
1285:
1286: if ($isIterableAtLeastOnce->yes()) {
1287: $arrayType = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
1288: }
1289: if ($this->isList->yes()) {
1290: $arrayType = AccessoryArrayListType::intersectWith($arrayType);
1291: }
1292:
1293: return $arrayType;
1294: }
1295:
1296: /**
1297: * @return self
1298: */
1299: public function getKeysArray(): Type
1300: {
1301: return $this->getKeysOrValuesArray($this->keyTypes);
1302: }
1303:
1304: /**
1305: * @return self
1306: */
1307: public function getValuesArray(): Type
1308: {
1309: return $this->getKeysOrValuesArray($this->valueTypes);
1310: }
1311:
1312: /**
1313: * @param array<int, Type> $types
1314: */
1315: private function getKeysOrValuesArray(array $types): self
1316: {
1317: $count = count($types);
1318: $autoIndexes = range($count - count($this->optionalKeys), $count);
1319: assert($autoIndexes !== []);
1320:
1321: if ($this->isList->yes()) {
1322: // Optimized version for lists: Assume that if a later key exists, then earlier keys also exist.
1323: $keyTypes = array_map(
1324: static fn (int $i): ConstantIntegerType => new ConstantIntegerType($i),
1325: array_keys($types),
1326: );
1327: return new self($keyTypes, $types, $autoIndexes, $this->optionalKeys, TrinaryLogic::createYes());
1328: }
1329:
1330: $keyTypes = [];
1331: $valueTypes = [];
1332: $optionalKeys = [];
1333: $maxIndex = 0;
1334:
1335: foreach ($types as $i => $type) {
1336: $keyTypes[] = new ConstantIntegerType($i);
1337:
1338: if ($this->isOptionalKey($maxIndex)) {
1339: // move $maxIndex to next non-optional key
1340: do {
1341: $maxIndex++;
1342: } while ($maxIndex < $count && $this->isOptionalKey($maxIndex));
1343: }
1344:
1345: if ($i === $maxIndex) {
1346: $valueTypes[] = $type;
1347: } else {
1348: $valueTypes[] = TypeCombinator::union(...array_slice($types, $i, $maxIndex - $i + 1));
1349: if ($maxIndex >= $count) {
1350: $optionalKeys[] = $i;
1351: }
1352: }
1353: $maxIndex++;
1354: }
1355:
1356: return new self($keyTypes, $valueTypes, $autoIndexes, $optionalKeys, TrinaryLogic::createYes());
1357: }
1358:
1359: /** @deprecated Use getArraySize() instead */
1360: public function count(): Type
1361: {
1362: return $this->getArraySize();
1363: }
1364:
1365: public function describe(VerbosityLevel $level): string
1366: {
1367: $describeValue = function (bool $truncate) use ($level): string {
1368: $items = [];
1369: $values = [];
1370: $exportValuesOnly = true;
1371: foreach ($this->keyTypes as $i => $keyType) {
1372: $valueType = $this->valueTypes[$i];
1373: if ($keyType->getValue() !== $i) {
1374: $exportValuesOnly = false;
1375: }
1376:
1377: $isOptional = $this->isOptionalKey($i);
1378: if ($isOptional) {
1379: $exportValuesOnly = false;
1380: }
1381:
1382: $keyDescription = $keyType->getValue();
1383: if (is_string($keyDescription)) {
1384: if (str_contains($keyDescription, '"')) {
1385: $keyDescription = sprintf('\'%s\'', $keyDescription);
1386: } elseif (str_contains($keyDescription, '\'')) {
1387: $keyDescription = sprintf('"%s"', $keyDescription);
1388: }
1389: }
1390:
1391: $valueTypeDescription = $valueType->describe($level);
1392: $items[] = sprintf('%s%s: %s', $keyDescription, $isOptional ? '?' : '', $valueTypeDescription);
1393: $values[] = $valueTypeDescription;
1394: }
1395:
1396: $append = '';
1397: if ($truncate && count($items) > self::DESCRIBE_LIMIT) {
1398: $items = array_slice($items, 0, self::DESCRIBE_LIMIT);
1399: $values = array_slice($values, 0, self::DESCRIBE_LIMIT);
1400: $append = ', ...';
1401: }
1402:
1403: return sprintf(
1404: 'array{%s%s}',
1405: implode(', ', $exportValuesOnly ? $values : $items),
1406: $append,
1407: );
1408: };
1409: return $level->handle(
1410: fn (): string => parent::describe($level),
1411: static fn (): string => $describeValue(true),
1412: static fn (): string => $describeValue(false),
1413: );
1414: }
1415:
1416: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1417: {
1418: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
1419: return $receivedType->inferTemplateTypesOn($this);
1420: }
1421:
1422: if ($receivedType instanceof self) {
1423: $typeMap = TemplateTypeMap::createEmpty();
1424: foreach ($this->keyTypes as $i => $keyType) {
1425: $valueType = $this->valueTypes[$i];
1426: if ($receivedType->hasOffsetValueType($keyType)->no()) {
1427: continue;
1428: }
1429: $receivedValueType = $receivedType->getOffsetValueType($keyType);
1430: $typeMap = $typeMap->union($valueType->inferTemplateTypes($receivedValueType));
1431: }
1432:
1433: return $typeMap;
1434: }
1435:
1436: return parent::inferTemplateTypes($receivedType);
1437: }
1438:
1439: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1440: {
1441: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
1442: $references = [];
1443:
1444: foreach ($this->keyTypes as $type) {
1445: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
1446: $references[] = $reference;
1447: }
1448: }
1449:
1450: foreach ($this->valueTypes as $type) {
1451: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
1452: $references[] = $reference;
1453: }
1454: }
1455:
1456: return $references;
1457: }
1458:
1459: public function traverse(callable $cb): Type
1460: {
1461: $valueTypes = [];
1462:
1463: $stillOriginal = true;
1464: foreach ($this->valueTypes as $valueType) {
1465: $transformedValueType = $cb($valueType);
1466: if ($transformedValueType !== $valueType) {
1467: $stillOriginal = false;
1468: }
1469:
1470: $valueTypes[] = $transformedValueType;
1471: }
1472:
1473: if ($stillOriginal) {
1474: return $this;
1475: }
1476:
1477: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1478: }
1479:
1480: public function traverseSimultaneously(Type $right, callable $cb): Type
1481: {
1482: if (!$right->isArray()->yes()) {
1483: return $this;
1484: }
1485:
1486: $valueTypes = [];
1487:
1488: $stillOriginal = true;
1489: foreach ($this->valueTypes as $i => $valueType) {
1490: $keyType = $this->keyTypes[$i];
1491: $transformedValueType = $cb($valueType, $right->getOffsetValueType($keyType));
1492: if ($transformedValueType !== $valueType) {
1493: $stillOriginal = false;
1494: }
1495:
1496: $valueTypes[] = $transformedValueType;
1497: }
1498:
1499: if ($stillOriginal) {
1500: return $this;
1501: }
1502:
1503: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1504: }
1505:
1506: public function isKeysSupersetOf(self $otherArray): bool
1507: {
1508: $keyTypesCount = count($this->keyTypes);
1509: $otherKeyTypesCount = count($otherArray->keyTypes);
1510:
1511: if ($keyTypesCount < $otherKeyTypesCount) {
1512: return false;
1513: }
1514:
1515: if ($otherKeyTypesCount === 0) {
1516: return $keyTypesCount === 0;
1517: }
1518:
1519: $failOnDifferentValueType = $keyTypesCount !== $otherKeyTypesCount || $keyTypesCount < 2;
1520:
1521: $keyTypes = $this->keyTypes;
1522:
1523: foreach ($otherArray->keyTypes as $j => $keyType) {
1524: $i = self::findKeyIndex($keyType, $keyTypes);
1525: if ($i === null) {
1526: return false;
1527: }
1528:
1529: unset($keyTypes[$i]);
1530:
1531: $valueType = $this->valueTypes[$i];
1532: $otherValueType = $otherArray->valueTypes[$j];
1533: if (!$otherValueType->isSuperTypeOf($valueType)->no()) {
1534: continue;
1535: }
1536:
1537: if ($failOnDifferentValueType) {
1538: return false;
1539: }
1540: $failOnDifferentValueType = true;
1541: }
1542:
1543: $requiredKeyCount = 0;
1544: foreach (array_keys($keyTypes) as $i) {
1545: if ($this->isOptionalKey($i)) {
1546: continue;
1547: }
1548:
1549: $requiredKeyCount++;
1550: if ($requiredKeyCount > 1) {
1551: return false;
1552: }
1553: }
1554:
1555: return true;
1556: }
1557:
1558: public function mergeWith(self $otherArray): self
1559: {
1560: // only call this after verifying isKeysSupersetOf
1561: $valueTypes = $this->valueTypes;
1562: $optionalKeys = $this->optionalKeys;
1563: foreach ($this->keyTypes as $i => $keyType) {
1564: $otherIndex = $otherArray->getKeyIndex($keyType);
1565: if ($otherIndex === null) {
1566: $optionalKeys[] = $i;
1567: continue;
1568: }
1569: if ($otherArray->isOptionalKey($otherIndex)) {
1570: $optionalKeys[] = $i;
1571: }
1572: $otherValueType = $otherArray->valueTypes[$otherIndex];
1573: $valueTypes[$i] = TypeCombinator::union($valueTypes[$i], $otherValueType);
1574: }
1575:
1576: $optionalKeys = array_values(array_unique($optionalKeys));
1577:
1578: $nextAutoIndexes = array_values(array_unique(array_merge($this->nextAutoIndexes, $otherArray->nextAutoIndexes)));
1579: sort($nextAutoIndexes);
1580:
1581: return new self($this->keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $this->isList->and($otherArray->isList));
1582: }
1583:
1584: /**
1585: * @param ConstantIntegerType|ConstantStringType $otherKeyType
1586: */
1587: private function getKeyIndex($otherKeyType): ?int
1588: {
1589: return self::findKeyIndex($otherKeyType, $this->keyTypes);
1590: }
1591:
1592: /**
1593: * @param ConstantIntegerType|ConstantStringType $otherKeyType
1594: * @param array<int, ConstantIntegerType|ConstantStringType> $keyTypes
1595: */
1596: private static function findKeyIndex($otherKeyType, array $keyTypes): ?int
1597: {
1598: foreach ($keyTypes as $i => $keyType) {
1599: if ($keyType->equals($otherKeyType)) {
1600: return $i;
1601: }
1602: }
1603:
1604: return null;
1605: }
1606:
1607: public function makeOffsetRequired(Type $offsetType): self
1608: {
1609: $offsetType = $offsetType->toArrayKey();
1610: $optionalKeys = $this->optionalKeys;
1611: foreach ($this->keyTypes as $i => $keyType) {
1612: if (!$keyType->equals($offsetType)) {
1613: continue;
1614: }
1615:
1616: foreach ($optionalKeys as $j => $key) {
1617: if ($i === $key) {
1618: unset($optionalKeys[$j]);
1619: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, array_values($optionalKeys), $this->isList);
1620: }
1621: }
1622:
1623: break;
1624: }
1625:
1626: return $this;
1627: }
1628:
1629: public function toPhpDocNode(): TypeNode
1630: {
1631: $items = [];
1632: $values = [];
1633: $exportValuesOnly = true;
1634: foreach ($this->keyTypes as $i => $keyType) {
1635: if ($keyType->getValue() !== $i) {
1636: $exportValuesOnly = false;
1637: }
1638: $keyPhpDocNode = $keyType->toPhpDocNode();
1639: if (!$keyPhpDocNode instanceof ConstTypeNode) {
1640: continue;
1641: }
1642: $valueType = $this->valueTypes[$i];
1643:
1644: /** @var ConstExprStringNode|ConstExprIntegerNode $keyNode */
1645: $keyNode = $keyPhpDocNode->constExpr;
1646: if ($keyNode instanceof ConstExprStringNode) {
1647: $value = $keyNode->value;
1648: if (self::isValidIdentifier($value)) {
1649: $keyNode = new IdentifierTypeNode($value);
1650: }
1651: }
1652:
1653: $isOptional = $this->isOptionalKey($i);
1654: if ($isOptional) {
1655: $exportValuesOnly = false;
1656: }
1657: $items[] = new ArrayShapeItemNode(
1658: $keyNode,
1659: $isOptional,
1660: $valueType->toPhpDocNode(),
1661: );
1662: $values[] = new ArrayShapeItemNode(
1663: null,
1664: $isOptional,
1665: $valueType->toPhpDocNode(),
1666: );
1667: }
1668:
1669: return new ArrayShapeNode($exportValuesOnly ? $values : $items);
1670: }
1671:
1672: public static function isValidIdentifier(string $value): bool
1673: {
1674: $result = Strings::match($value, '~^(?:[\\\\]?+[a-z_\\x80-\\xFF][0-9a-z_\\x80-\\xFF-]*+)++$~si');
1675:
1676: return $result !== null;
1677: }
1678:
1679: public function getFiniteTypes(): array
1680: {
1681: $arraysArraysForCombinations = [];
1682: $count = 0;
1683: foreach ($this->getAllArrays() as $array) {
1684: $values = $array->getValueTypes();
1685: $arraysForCombinations = [];
1686: $combinationCount = 1;
1687: foreach ($values as $valueType) {
1688: $finiteTypes = $valueType->getFiniteTypes();
1689: if ($finiteTypes === []) {
1690: return [];
1691: }
1692: $arraysForCombinations[] = $finiteTypes;
1693: $combinationCount *= count($finiteTypes);
1694: }
1695: $arraysArraysForCombinations[] = $arraysForCombinations;
1696: $count += $combinationCount;
1697: }
1698:
1699: if ($count > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1700: return [];
1701: }
1702:
1703: $finiteTypes = [];
1704: foreach ($arraysArraysForCombinations as $arraysForCombinations) {
1705: $combinations = CombinationsHelper::combinations($arraysForCombinations);
1706: foreach ($combinations as $combination) {
1707: $builder = ConstantArrayTypeBuilder::createEmpty();
1708: foreach ($combination as $i => $v) {
1709: $builder->setOffsetValueType($this->keyTypes[$i], $v);
1710: }
1711: $finiteTypes[] = $builder->getArray();
1712: }
1713: }
1714:
1715: return $finiteTypes;
1716: }
1717:
1718: /**
1719: * @param mixed[] $properties
1720: */
1721: public static function __set_state(array $properties): Type
1722: {
1723: return new self($properties['keyTypes'], $properties['valueTypes'], $properties['nextAutoIndexes'] ?? $properties['nextAutoIndex'], $properties['optionalKeys'] ?? [], $properties['isList'] ?? TrinaryLogic::createNo());
1724: }
1725:
1726: }
1727: