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\Callables\FunctionCallableVariant;
18: use PHPStan\Reflection\ClassMemberAccessAnswerer;
19: use PHPStan\Reflection\InaccessibleMethod;
20: use PHPStan\Reflection\InitializerExprTypeResolver;
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: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
475: {
476: $typeAndMethodNames = $this->findTypeAndMethodNames();
477: if ($typeAndMethodNames === []) {
478: throw new ShouldNotHappenException();
479: }
480:
481: $acceptors = [];
482: foreach ($typeAndMethodNames as $typeAndMethodName) {
483: if ($typeAndMethodName->isUnknown() || !$typeAndMethodName->getCertainty()->yes()) {
484: $acceptors[] = new TrivialParametersAcceptor();
485: continue;
486: }
487:
488: $method = $typeAndMethodName->getType()
489: ->getMethod($typeAndMethodName->getMethod(), $scope);
490:
491: if (!$scope->canCallMethod($method)) {
492: $acceptors[] = new InaccessibleMethod($method);
493: continue;
494: }
495:
496: array_push($acceptors, ...FunctionCallableVariant::createFromVariants($method, $method->getVariants()));
497: }
498:
499: return $acceptors;
500: }
501:
502: /**
503: * @return array{Type, Type}|array{}
504: */
505: private function getClassOrObjectAndMethods(): array
506: {
507: if (count($this->keyTypes) !== 2) {
508: return [];
509: }
510:
511: $classOrObject = null;
512: $method = null;
513: foreach ($this->keyTypes as $i => $keyType) {
514: if ($keyType->isSuperTypeOf(new ConstantIntegerType(0))->yes()) {
515: $classOrObject = $this->valueTypes[$i];
516: continue;
517: }
518:
519: if (!$keyType->isSuperTypeOf(new ConstantIntegerType(1))->yes()) {
520: continue;
521: }
522:
523: $method = $this->valueTypes[$i];
524: }
525:
526: if ($classOrObject === null || $method === null) {
527: return [];
528: }
529:
530: return [$classOrObject, $method];
531: }
532:
533: /** @deprecated Use findTypeAndMethodNames() instead */
534: public function findTypeAndMethodName(): ?ConstantArrayTypeAndMethod
535: {
536: $callableArray = $this->getClassOrObjectAndMethods();
537: if ($callableArray === []) {
538: return null;
539: }
540:
541: [$classOrObject, $method] = $callableArray;
542: if (!$method instanceof ConstantStringType) {
543: return ConstantArrayTypeAndMethod::createUnknown();
544: }
545:
546: $type = $classOrObject->getObjectTypeOrClassStringObjectType();
547: if (!$type->isObject()->yes()) {
548: return ConstantArrayTypeAndMethod::createUnknown();
549: }
550:
551: $has = $type->hasMethod($method->getValue());
552: if (!$has->no()) {
553: if ($this->isOptionalKey(0) || $this->isOptionalKey(1)) {
554: $has = $has->and(TrinaryLogic::createMaybe());
555: }
556:
557: return ConstantArrayTypeAndMethod::createConcrete($type, $method->getValue(), $has);
558: }
559:
560: return null;
561: }
562:
563: /** @return ConstantArrayTypeAndMethod[] */
564: public function findTypeAndMethodNames(): array
565: {
566: $callableArray = $this->getClassOrObjectAndMethods();
567: if ($callableArray === []) {
568: return [];
569: }
570:
571: [$classOrObject, $methods] = $callableArray;
572: if (count($methods->getConstantStrings()) === 0) {
573: return [ConstantArrayTypeAndMethod::createUnknown()];
574: }
575:
576: $type = $classOrObject->getObjectTypeOrClassStringObjectType();
577: if (!$type->isObject()->yes()) {
578: return [ConstantArrayTypeAndMethod::createUnknown()];
579: }
580:
581: $typeAndMethods = [];
582: $phpVersion = PhpVersionStaticAccessor::getInstance();
583: foreach ($methods->getConstantStrings() as $method) {
584: $has = $type->hasMethod($method->getValue());
585: if ($has->no()) {
586: continue;
587: }
588:
589: if (
590: BleedingEdgeToggle::isBleedingEdge()
591: && $has->yes()
592: && !$phpVersion->supportsCallableInstanceMethods()
593: ) {
594: $methodReflection = $type->getMethod($method->getValue(), new OutOfClassScope());
595: if ($classOrObject->isString()->yes() && !$methodReflection->isStatic()) {
596: continue;
597: }
598: }
599:
600: if ($this->isOptionalKey(0) || $this->isOptionalKey(1)) {
601: $has = $has->and(TrinaryLogic::createMaybe());
602: }
603:
604: $typeAndMethods[] = ConstantArrayTypeAndMethod::createConcrete($type, $method->getValue(), $has);
605: }
606:
607: return $typeAndMethods;
608: }
609:
610: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
611: {
612: $offsetType = $offsetType->toArrayKey();
613:
614: $result = TrinaryLogic::createNo();
615: foreach ($this->keyTypes as $i => $keyType) {
616: if (
617: $keyType instanceof ConstantIntegerType
618: && !$offsetType->isString()->no()
619: && $offsetType->isConstantScalarValue()->no()
620: ) {
621: return TrinaryLogic::createMaybe();
622: }
623:
624: $has = $keyType->isSuperTypeOf($offsetType);
625: if ($has->yes()) {
626: if ($this->isOptionalKey($i)) {
627: return TrinaryLogic::createMaybe();
628: }
629: return TrinaryLogic::createYes();
630: }
631: if (!$has->maybe()) {
632: continue;
633: }
634:
635: $result = TrinaryLogic::createMaybe();
636: }
637:
638: return $result;
639: }
640:
641: public function getOffsetValueType(Type $offsetType): Type
642: {
643: $offsetType = $offsetType->toArrayKey();
644: $matchingValueTypes = [];
645: $all = true;
646: foreach ($this->keyTypes as $i => $keyType) {
647: if ($keyType->isSuperTypeOf($offsetType)->no()) {
648: $all = false;
649: continue;
650: }
651:
652: $matchingValueTypes[] = $this->valueTypes[$i];
653: }
654:
655: if ($all) {
656: if (count($this->keyTypes) === 0) {
657: return new ErrorType();
658: }
659:
660: return $this->getIterableValueType();
661: }
662:
663: if (count($matchingValueTypes) > 0) {
664: $type = TypeCombinator::union(...$matchingValueTypes);
665: if ($type instanceof ErrorType) {
666: return new MixedType();
667: }
668:
669: return $type;
670: }
671:
672: return new ErrorType(); // undefined offset
673: }
674:
675: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
676: {
677: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
678: $builder->setOffsetValueType($offsetType, $valueType);
679:
680: return $builder->getArray();
681: }
682:
683: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
684: {
685: $offsetType = $offsetType->toArrayKey();
686: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
687: foreach ($this->keyTypes as $keyType) {
688: if ($offsetType->isSuperTypeOf($keyType)->no()) {
689: continue;
690: }
691:
692: $builder->setOffsetValueType($keyType, $valueType);
693: }
694:
695: return $builder->getArray();
696: }
697:
698: public function unsetOffset(Type $offsetType): Type
699: {
700: $offsetType = $offsetType->toArrayKey();
701: if ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType) {
702: foreach ($this->keyTypes as $i => $keyType) {
703: if ($keyType->getValue() !== $offsetType->getValue()) {
704: continue;
705: }
706:
707: $keyTypes = $this->keyTypes;
708: unset($keyTypes[$i]);
709: $valueTypes = $this->valueTypes;
710: unset($valueTypes[$i]);
711:
712: $newKeyTypes = [];
713: $newValueTypes = [];
714: $newOptionalKeys = [];
715:
716: $k = 0;
717: foreach ($keyTypes as $j => $newKeyType) {
718: $newKeyTypes[] = $newKeyType;
719: $newValueTypes[] = $valueTypes[$j];
720: if (in_array($j, $this->optionalKeys, true)) {
721: $newOptionalKeys[] = $k;
722: }
723: $k++;
724: }
725:
726: return new self($newKeyTypes, $newValueTypes, $this->nextAutoIndexes, $newOptionalKeys, TrinaryLogic::createNo());
727: }
728:
729: return $this;
730: }
731:
732: $constantScalars = $offsetType->getConstantScalarTypes();
733: if (count($constantScalars) > 0) {
734: $optionalKeys = $this->optionalKeys;
735:
736: foreach ($constantScalars as $constantScalar) {
737: $constantScalar = $constantScalar->toArrayKey();
738: if (!$constantScalar instanceof ConstantIntegerType && !$constantScalar instanceof ConstantStringType) {
739: continue;
740: }
741:
742: foreach ($this->keyTypes as $i => $keyType) {
743: if ($keyType->getValue() !== $constantScalar->getValue()) {
744: continue;
745: }
746:
747: if (in_array($i, $optionalKeys, true)) {
748: continue 2;
749: }
750:
751: $optionalKeys[] = $i;
752: }
753: }
754:
755: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, TrinaryLogic::createNo());
756: }
757:
758: $optionalKeys = $this->optionalKeys;
759: $isList = $this->isList;
760: foreach ($this->keyTypes as $i => $keyType) {
761: if (!$offsetType->isSuperTypeOf($keyType)->yes()) {
762: continue;
763: }
764: $optionalKeys[] = $i;
765: $isList = TrinaryLogic::createNo();
766: }
767: $optionalKeys = array_values(array_unique($optionalKeys));
768:
769: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, $isList);
770: }
771:
772: public function fillKeysArray(Type $valueType): Type
773: {
774: $builder = ConstantArrayTypeBuilder::createEmpty();
775:
776: foreach ($this->valueTypes as $i => $keyType) {
777: if ($keyType->isInteger()->no()) {
778: $stringKeyType = $keyType->toString();
779: if ($stringKeyType instanceof ErrorType) {
780: return $stringKeyType;
781: }
782:
783: $builder->setOffsetValueType($stringKeyType, $valueType, $this->isOptionalKey($i));
784: } else {
785: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i));
786: }
787: }
788:
789: return $builder->getArray();
790: }
791:
792: public function flipArray(): Type
793: {
794: $builder = ConstantArrayTypeBuilder::createEmpty();
795:
796: foreach ($this->keyTypes as $i => $keyType) {
797: $valueType = $this->valueTypes[$i];
798: $builder->setOffsetValueType(
799: $valueType->toArrayKey(),
800: $keyType,
801: $this->isOptionalKey($i),
802: );
803: }
804:
805: return $builder->getArray();
806: }
807:
808: public function intersectKeyArray(Type $otherArraysType): Type
809: {
810: $builder = ConstantArrayTypeBuilder::createEmpty();
811:
812: foreach ($this->keyTypes as $i => $keyType) {
813: $valueType = $this->valueTypes[$i];
814: $has = $otherArraysType->hasOffsetValueType($keyType);
815: if ($has->no()) {
816: continue;
817: }
818: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i) || !$has->yes());
819: }
820:
821: return $builder->getArray();
822: }
823:
824: public function popArray(): Type
825: {
826: return $this->removeLastElements(1);
827: }
828:
829: public function searchArray(Type $needleType): Type
830: {
831: $matches = [];
832: $hasIdenticalValue = false;
833:
834: foreach ($this->valueTypes as $index => $valueType) {
835: $isNeedleSuperType = $valueType->isSuperTypeOf($needleType);
836: if ($isNeedleSuperType->no()) {
837: continue;
838: }
839:
840: if ($needleType instanceof ConstantScalarType && $valueType instanceof ConstantScalarType
841: && $needleType->getValue() === $valueType->getValue()
842: && !$this->isOptionalKey($index)
843: ) {
844: $hasIdenticalValue = true;
845: }
846:
847: $matches[] = $this->keyTypes[$index];
848: }
849:
850: if (count($matches) > 0) {
851: if ($hasIdenticalValue) {
852: return TypeCombinator::union(...$matches);
853: }
854:
855: return TypeCombinator::union(new ConstantBooleanType(false), ...$matches);
856: }
857:
858: return new ConstantBooleanType(false);
859: }
860:
861: public function shiftArray(): Type
862: {
863: return $this->removeFirstElements(1);
864: }
865:
866: public function shuffleArray(): Type
867: {
868: $valuesArray = $this->getValuesArray();
869:
870: $isIterableAtLeastOnce = $valuesArray->isIterableAtLeastOnce();
871: if ($isIterableAtLeastOnce->no()) {
872: return $valuesArray;
873: }
874:
875: $generalizedArray = new ArrayType($valuesArray->getIterableKeyType(), $valuesArray->getItemType());
876:
877: if ($isIterableAtLeastOnce->yes()) {
878: $generalizedArray = TypeCombinator::intersect($generalizedArray, new NonEmptyArrayType());
879: }
880: if ($valuesArray->isList->yes()) {
881: $generalizedArray = AccessoryArrayListType::intersectWith($generalizedArray);
882: }
883:
884: return $generalizedArray;
885: }
886:
887: public function isIterableAtLeastOnce(): TrinaryLogic
888: {
889: $keysCount = count($this->keyTypes);
890: if ($keysCount === 0) {
891: return TrinaryLogic::createNo();
892: }
893:
894: $optionalKeysCount = count($this->optionalKeys);
895: if ($optionalKeysCount < $keysCount) {
896: return TrinaryLogic::createYes();
897: }
898:
899: return TrinaryLogic::createMaybe();
900: }
901:
902: public function getArraySize(): Type
903: {
904: $optionalKeysCount = count($this->optionalKeys);
905: $totalKeysCount = count($this->getKeyTypes());
906: if ($optionalKeysCount === 0) {
907: return new ConstantIntegerType($totalKeysCount);
908: }
909:
910: return IntegerRangeType::fromInterval($totalKeysCount - $optionalKeysCount, $totalKeysCount);
911: }
912:
913: public function getFirstIterableKeyType(): Type
914: {
915: $keyTypes = [];
916: foreach ($this->keyTypes as $i => $keyType) {
917: $keyTypes[] = $keyType;
918: if (!$this->isOptionalKey($i)) {
919: break;
920: }
921: }
922:
923: return TypeCombinator::union(...$keyTypes);
924: }
925:
926: public function getLastIterableKeyType(): Type
927: {
928: $keyTypes = [];
929: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
930: $keyTypes[] = $this->keyTypes[$i];
931: if (!$this->isOptionalKey($i)) {
932: break;
933: }
934: }
935:
936: return TypeCombinator::union(...$keyTypes);
937: }
938:
939: public function getFirstIterableValueType(): Type
940: {
941: $valueTypes = [];
942: foreach ($this->valueTypes as $i => $valueType) {
943: $valueTypes[] = $valueType;
944: if (!$this->isOptionalKey($i)) {
945: break;
946: }
947: }
948:
949: return TypeCombinator::union(...$valueTypes);
950: }
951:
952: public function getLastIterableValueType(): Type
953: {
954: $valueTypes = [];
955: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
956: $valueTypes[] = $this->valueTypes[$i];
957: if (!$this->isOptionalKey($i)) {
958: break;
959: }
960: }
961:
962: return TypeCombinator::union(...$valueTypes);
963: }
964:
965: public function isConstantArray(): TrinaryLogic
966: {
967: return TrinaryLogic::createYes();
968: }
969:
970: public function isList(): TrinaryLogic
971: {
972: return $this->isList;
973: }
974:
975: /** @deprecated Use popArray() instead */
976: public function removeLast(): self
977: {
978: return $this->removeLastElements(1);
979: }
980:
981: /** @param positive-int $length */
982: private function removeLastElements(int $length): self
983: {
984: $keyTypesCount = count($this->keyTypes);
985: if ($keyTypesCount === 0) {
986: return $this;
987: }
988:
989: $keyTypes = $this->keyTypes;
990: $valueTypes = $this->valueTypes;
991: $optionalKeys = $this->optionalKeys;
992: $nextAutoindex = $this->nextAutoIndexes;
993:
994: $optionalKeysRemoved = 0;
995: $newLength = $keyTypesCount - $length;
996: for ($i = $keyTypesCount - 1; $i >= 0; $i--) {
997: $isOptional = $this->isOptionalKey($i);
998:
999: if ($i >= $newLength) {
1000: if ($isOptional) {
1001: $optionalKeysRemoved++;
1002: foreach ($optionalKeys as $key => $value) {
1003: if ($value === $i) {
1004: unset($optionalKeys[$key]);
1005: break;
1006: }
1007: }
1008: }
1009:
1010: $removedKeyType = array_pop($keyTypes);
1011: array_pop($valueTypes);
1012: $nextAutoindex = $removedKeyType instanceof ConstantIntegerType
1013: ? $removedKeyType->getValue()
1014: : $this->getNextAutoIndex(); // @phpstan-ignore method.deprecated
1015: continue;
1016: }
1017:
1018: if ($isOptional || $optionalKeysRemoved <= 0) {
1019: continue;
1020: }
1021:
1022: $optionalKeys[] = $i;
1023: $optionalKeysRemoved--;
1024: }
1025:
1026: return new self(
1027: $keyTypes,
1028: $valueTypes,
1029: $nextAutoindex,
1030: array_values($optionalKeys),
1031: $this->isList,
1032: );
1033: }
1034:
1035: /** @deprecated Use shiftArray() instead */
1036: public function removeFirst(): self
1037: {
1038: return $this->removeFirstElements(1);
1039: }
1040:
1041: /** @param positive-int $length */
1042: private function removeFirstElements(int $length, bool $reindex = true): self
1043: {
1044: $builder = ConstantArrayTypeBuilder::createEmpty();
1045:
1046: $optionalKeysIgnored = 0;
1047: foreach ($this->keyTypes as $i => $keyType) {
1048: $isOptional = $this->isOptionalKey($i);
1049: if ($i <= $length - 1) {
1050: if ($isOptional) {
1051: $optionalKeysIgnored++;
1052: }
1053: continue;
1054: }
1055:
1056: if (!$isOptional && $optionalKeysIgnored > 0) {
1057: $isOptional = true;
1058: $optionalKeysIgnored--;
1059: }
1060:
1061: $valueType = $this->valueTypes[$i];
1062: if ($reindex && $keyType instanceof ConstantIntegerType) {
1063: $keyType = null;
1064: }
1065:
1066: $builder->setOffsetValueType($keyType, $valueType, $isOptional);
1067: }
1068:
1069: $array = $builder->getArray();
1070: if (!$array instanceof self) {
1071: throw new ShouldNotHappenException();
1072: }
1073:
1074: return $array;
1075: }
1076:
1077: public function slice(int $offset, ?int $limit, bool $preserveKeys = false): self
1078: {
1079: $keyTypesCount = count($this->keyTypes);
1080: if ($keyTypesCount === 0) {
1081: return $this;
1082: }
1083:
1084: $limit ??= $keyTypesCount;
1085: if ($limit < 0) {
1086: // Negative limits prevent access to the most right n elements
1087: return $this->removeLastElements($limit * -1)
1088: ->slice($offset, null, $preserveKeys);
1089: }
1090:
1091: if ($keyTypesCount + $offset <= 0) {
1092: // A negative offset cannot reach left outside the array
1093: $offset = 0;
1094: }
1095:
1096: if ($offset < 0) {
1097: /*
1098: * Transforms the problem with the negative offset in one with a positive offset using array reversion.
1099: * The reason is belows handling of optional keys which works only from left to right.
1100: *
1101: * e.g.
1102: * array{a: 0, b: 1, c: 2, d: 3, e: 4}
1103: * with offset -4 and limit 2 (which would be sliced to array{b: 1, c: 2})
1104: *
1105: * is transformed via reversion to
1106: *
1107: * array{e: 4, d: 3, c: 2, b: 1, a: 0}
1108: * with offset 2 and limit 2 (which will be sliced to array{c: 2, b: 1} and then reversed again)
1109: */
1110: $offset *= -1;
1111: $reversedLimit = min($limit, $offset);
1112: $reversedOffset = $offset - $reversedLimit;
1113: return $this->reverse(true)
1114: ->slice($reversedOffset, $reversedLimit, $preserveKeys)
1115: ->reverse(true);
1116: }
1117:
1118: if ($offset > 0) {
1119: return $this->removeFirstElements($offset, false)
1120: ->slice(0, $limit, $preserveKeys);
1121: }
1122:
1123: $builder = ConstantArrayTypeBuilder::createEmpty();
1124:
1125: $nonOptionalElementsCount = 0;
1126: $hasOptional = false;
1127: for ($i = 0; $nonOptionalElementsCount < $limit && $i < $keyTypesCount; $i++) {
1128: $isOptional = $this->isOptionalKey($i);
1129: if (!$isOptional) {
1130: $nonOptionalElementsCount++;
1131: } else {
1132: $hasOptional = true;
1133: }
1134:
1135: $isLastElement = $nonOptionalElementsCount >= $limit || $i + 1 >= $keyTypesCount;
1136: if ($isLastElement && $limit < $keyTypesCount && $hasOptional) {
1137: // If the slice is not full yet, but has at least one optional key
1138: // the last non-optional element is going to be optional.
1139: // Otherwise, it would not fit into the slice if previous non-optional keys are there.
1140: $isOptional = true;
1141: }
1142:
1143: $builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i], $isOptional);
1144: }
1145:
1146: $slice = $builder->getArray();
1147: if (!$slice instanceof self) {
1148: throw new ShouldNotHappenException();
1149: }
1150:
1151: return $preserveKeys ? $slice : $slice->reindex();
1152: }
1153:
1154: public function reverse(bool $preserveKeys = false): self
1155: {
1156: $keyTypesReversed = array_reverse($this->keyTypes, true);
1157: $keyTypes = array_values($keyTypesReversed);
1158: $keyTypesReversedKeys = array_keys($keyTypesReversed);
1159: $optionalKeys = array_map(static fn (int $optionalKey): int => $keyTypesReversedKeys[$optionalKey], $this->optionalKeys);
1160:
1161: $reversed = new self($keyTypes, array_reverse($this->valueTypes), $this->nextAutoIndexes, $optionalKeys, TrinaryLogic::createNo());
1162:
1163: return $preserveKeys ? $reversed : $reversed->reindex();
1164: }
1165:
1166: /** @param positive-int $length */
1167: public function chunk(int $length, bool $preserveKeys = false): self
1168: {
1169: $builder = ConstantArrayTypeBuilder::createEmpty();
1170:
1171: $keyTypesCount = count($this->keyTypes);
1172: for ($i = 0; $i < $keyTypesCount; $i += $length) {
1173: $chunk = $this->slice($i, $length, true);
1174: $builder->setOffsetValueType(null, $preserveKeys ? $chunk : $chunk->getValuesArray());
1175: }
1176:
1177: $chunks = $builder->getArray();
1178: if (!$chunks instanceof self) {
1179: throw new ShouldNotHappenException();
1180: }
1181:
1182: return $chunks;
1183: }
1184:
1185: private function reindex(): self
1186: {
1187: $keyTypes = [];
1188: $autoIndex = 0;
1189:
1190: foreach ($this->keyTypes as $keyType) {
1191: if (!$keyType instanceof ConstantIntegerType) {
1192: $keyTypes[] = $keyType;
1193: continue;
1194: }
1195:
1196: $keyTypes[] = new ConstantIntegerType($autoIndex);
1197: $autoIndex++;
1198: }
1199:
1200: return new self($keyTypes, $this->valueTypes, [$autoIndex], $this->optionalKeys, TrinaryLogic::createYes());
1201: }
1202:
1203: public function toBoolean(): BooleanType
1204: {
1205: return $this->getArraySize()->toBoolean();
1206: }
1207:
1208: public function toInteger(): Type
1209: {
1210: return $this->toBoolean()->toInteger();
1211: }
1212:
1213: public function toFloat(): Type
1214: {
1215: return $this->toBoolean()->toFloat();
1216: }
1217:
1218: public function generalize(GeneralizePrecision $precision): Type
1219: {
1220: if (count($this->keyTypes) === 0) {
1221: return $this;
1222: }
1223:
1224: if ($precision->isTemplateArgument()) {
1225: return $this->traverse(static fn (Type $type) => $type->generalize($precision));
1226: }
1227:
1228: $arrayType = new ArrayType(
1229: $this->getIterableKeyType()->generalize($precision),
1230: $this->getItemType()->generalize($precision),
1231: );
1232:
1233: $keyTypesCount = count($this->keyTypes);
1234: $optionalKeysCount = count($this->optionalKeys);
1235:
1236: $accessoryTypes = [];
1237: if ($precision->isMoreSpecific() && ($keyTypesCount - $optionalKeysCount) < 32) {
1238: foreach ($this->keyTypes as $i => $keyType) {
1239: if ($this->isOptionalKey($i)) {
1240: continue;
1241: }
1242:
1243: $accessoryTypes[] = new HasOffsetValueType($keyType, $this->valueTypes[$i]->generalize($precision));
1244: }
1245: } elseif ($keyTypesCount > $optionalKeysCount) {
1246: $accessoryTypes[] = new NonEmptyArrayType();
1247: }
1248:
1249: if ($this->isList()->yes()) {
1250: $arrayType = AccessoryArrayListType::intersectWith($arrayType);
1251: }
1252:
1253: if (count($accessoryTypes) > 0) {
1254: return TypeCombinator::intersect($arrayType, ...$accessoryTypes);
1255: }
1256:
1257: return $arrayType;
1258: }
1259:
1260: /**
1261: * @return self
1262: */
1263: public function generalizeValues(): ArrayType
1264: {
1265: $valueTypes = [];
1266: foreach ($this->valueTypes as $valueType) {
1267: $valueTypes[] = $valueType->generalize(GeneralizePrecision::lessSpecific());
1268: }
1269:
1270: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1271: }
1272:
1273: /** @deprecated */
1274: public function generalizeToArray(): Type
1275: {
1276: $isIterableAtLeastOnce = $this->isIterableAtLeastOnce();
1277: if ($isIterableAtLeastOnce->no()) {
1278: return $this;
1279: }
1280:
1281: $arrayType = new ArrayType($this->getIterableKeyType(), $this->getItemType());
1282:
1283: if ($isIterableAtLeastOnce->yes()) {
1284: $arrayType = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
1285: }
1286: if ($this->isList->yes()) {
1287: $arrayType = AccessoryArrayListType::intersectWith($arrayType);
1288: }
1289:
1290: return $arrayType;
1291: }
1292:
1293: /**
1294: * @return self
1295: */
1296: public function getKeysArray(): Type
1297: {
1298: return $this->getKeysOrValuesArray($this->keyTypes);
1299: }
1300:
1301: /**
1302: * @return self
1303: */
1304: public function getValuesArray(): Type
1305: {
1306: return $this->getKeysOrValuesArray($this->valueTypes);
1307: }
1308:
1309: /**
1310: * @param array<int, Type> $types
1311: */
1312: private function getKeysOrValuesArray(array $types): self
1313: {
1314: $count = count($types);
1315: $autoIndexes = range($count - count($this->optionalKeys), $count);
1316: assert($autoIndexes !== []);
1317:
1318: if ($this->isList->yes()) {
1319: // Optimized version for lists: Assume that if a later key exists, then earlier keys also exist.
1320: $keyTypes = array_map(
1321: static fn (int $i): ConstantIntegerType => new ConstantIntegerType($i),
1322: array_keys($types),
1323: );
1324: return new self($keyTypes, $types, $autoIndexes, $this->optionalKeys, TrinaryLogic::createYes());
1325: }
1326:
1327: $keyTypes = [];
1328: $valueTypes = [];
1329: $optionalKeys = [];
1330: $maxIndex = 0;
1331:
1332: foreach ($types as $i => $type) {
1333: $keyTypes[] = new ConstantIntegerType($i);
1334:
1335: if ($this->isOptionalKey($maxIndex)) {
1336: // move $maxIndex to next non-optional key
1337: do {
1338: $maxIndex++;
1339: } while ($maxIndex < $count && $this->isOptionalKey($maxIndex));
1340: }
1341:
1342: if ($i === $maxIndex) {
1343: $valueTypes[] = $type;
1344: } else {
1345: $valueTypes[] = TypeCombinator::union(...array_slice($types, $i, $maxIndex - $i + 1));
1346: if ($maxIndex >= $count) {
1347: $optionalKeys[] = $i;
1348: }
1349: }
1350: $maxIndex++;
1351: }
1352:
1353: return new self($keyTypes, $valueTypes, $autoIndexes, $optionalKeys, TrinaryLogic::createYes());
1354: }
1355:
1356: /** @deprecated Use getArraySize() instead */
1357: public function count(): Type
1358: {
1359: return $this->getArraySize();
1360: }
1361:
1362: public function describe(VerbosityLevel $level): string
1363: {
1364: $describeValue = function (bool $truncate) use ($level): string {
1365: $items = [];
1366: $values = [];
1367: $exportValuesOnly = true;
1368: foreach ($this->keyTypes as $i => $keyType) {
1369: $valueType = $this->valueTypes[$i];
1370: if ($keyType->getValue() !== $i) {
1371: $exportValuesOnly = false;
1372: }
1373:
1374: $isOptional = $this->isOptionalKey($i);
1375: if ($isOptional) {
1376: $exportValuesOnly = false;
1377: }
1378:
1379: $keyDescription = $keyType->getValue();
1380: if (is_string($keyDescription)) {
1381: if (str_contains($keyDescription, '"')) {
1382: $keyDescription = sprintf('\'%s\'', $keyDescription);
1383: } elseif (str_contains($keyDescription, '\'')) {
1384: $keyDescription = sprintf('"%s"', $keyDescription);
1385: }
1386: }
1387:
1388: $valueTypeDescription = $valueType->describe($level);
1389: $items[] = sprintf('%s%s: %s', $keyDescription, $isOptional ? '?' : '', $valueTypeDescription);
1390: $values[] = $valueTypeDescription;
1391: }
1392:
1393: $append = '';
1394: if ($truncate && count($items) > self::DESCRIBE_LIMIT) {
1395: $items = array_slice($items, 0, self::DESCRIBE_LIMIT);
1396: $values = array_slice($values, 0, self::DESCRIBE_LIMIT);
1397: $append = ', ...';
1398: }
1399:
1400: return sprintf(
1401: 'array{%s%s}',
1402: implode(', ', $exportValuesOnly ? $values : $items),
1403: $append,
1404: );
1405: };
1406: return $level->handle(
1407: fn (): string => parent::describe($level),
1408: static fn (): string => $describeValue(true),
1409: static fn (): string => $describeValue(false),
1410: );
1411: }
1412:
1413: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1414: {
1415: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
1416: return $receivedType->inferTemplateTypesOn($this);
1417: }
1418:
1419: if ($receivedType instanceof self) {
1420: $typeMap = TemplateTypeMap::createEmpty();
1421: foreach ($this->keyTypes as $i => $keyType) {
1422: $valueType = $this->valueTypes[$i];
1423: if ($receivedType->hasOffsetValueType($keyType)->no()) {
1424: continue;
1425: }
1426: $receivedValueType = $receivedType->getOffsetValueType($keyType);
1427: $typeMap = $typeMap->union($valueType->inferTemplateTypes($receivedValueType));
1428: }
1429:
1430: return $typeMap;
1431: }
1432:
1433: return parent::inferTemplateTypes($receivedType);
1434: }
1435:
1436: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1437: {
1438: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
1439: $references = [];
1440:
1441: foreach ($this->keyTypes as $type) {
1442: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
1443: $references[] = $reference;
1444: }
1445: }
1446:
1447: foreach ($this->valueTypes as $type) {
1448: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
1449: $references[] = $reference;
1450: }
1451: }
1452:
1453: return $references;
1454: }
1455:
1456: public function traverse(callable $cb): Type
1457: {
1458: $valueTypes = [];
1459:
1460: $stillOriginal = true;
1461: foreach ($this->valueTypes as $valueType) {
1462: $transformedValueType = $cb($valueType);
1463: if ($transformedValueType !== $valueType) {
1464: $stillOriginal = false;
1465: }
1466:
1467: $valueTypes[] = $transformedValueType;
1468: }
1469:
1470: if ($stillOriginal) {
1471: return $this;
1472: }
1473:
1474: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1475: }
1476:
1477: public function traverseSimultaneously(Type $right, callable $cb): Type
1478: {
1479: if (!$right->isArray()->yes()) {
1480: return $this;
1481: }
1482:
1483: $valueTypes = [];
1484:
1485: $stillOriginal = true;
1486: foreach ($this->valueTypes as $i => $valueType) {
1487: $keyType = $this->keyTypes[$i];
1488: $transformedValueType = $cb($valueType, $right->getOffsetValueType($keyType));
1489: if ($transformedValueType !== $valueType) {
1490: $stillOriginal = false;
1491: }
1492:
1493: $valueTypes[] = $transformedValueType;
1494: }
1495:
1496: if ($stillOriginal) {
1497: return $this;
1498: }
1499:
1500: return new self($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList);
1501: }
1502:
1503: public function isKeysSupersetOf(self $otherArray): bool
1504: {
1505: $keyTypesCount = count($this->keyTypes);
1506: $otherKeyTypesCount = count($otherArray->keyTypes);
1507:
1508: if ($keyTypesCount < $otherKeyTypesCount) {
1509: return false;
1510: }
1511:
1512: if ($otherKeyTypesCount === 0) {
1513: return $keyTypesCount === 0;
1514: }
1515:
1516: $failOnDifferentValueType = $keyTypesCount !== $otherKeyTypesCount || $keyTypesCount < 2;
1517:
1518: $keyTypes = $this->keyTypes;
1519:
1520: foreach ($otherArray->keyTypes as $j => $keyType) {
1521: $i = self::findKeyIndex($keyType, $keyTypes);
1522: if ($i === null) {
1523: return false;
1524: }
1525:
1526: unset($keyTypes[$i]);
1527:
1528: $valueType = $this->valueTypes[$i];
1529: $otherValueType = $otherArray->valueTypes[$j];
1530: if (!$otherValueType->isSuperTypeOf($valueType)->no()) {
1531: continue;
1532: }
1533:
1534: if ($failOnDifferentValueType) {
1535: return false;
1536: }
1537: $failOnDifferentValueType = true;
1538: }
1539:
1540: $requiredKeyCount = 0;
1541: foreach (array_keys($keyTypes) as $i) {
1542: if ($this->isOptionalKey($i)) {
1543: continue;
1544: }
1545:
1546: $requiredKeyCount++;
1547: if ($requiredKeyCount > 1) {
1548: return false;
1549: }
1550: }
1551:
1552: return true;
1553: }
1554:
1555: public function mergeWith(self $otherArray): self
1556: {
1557: // only call this after verifying isKeysSupersetOf
1558: $valueTypes = $this->valueTypes;
1559: $optionalKeys = $this->optionalKeys;
1560: foreach ($this->keyTypes as $i => $keyType) {
1561: $otherIndex = $otherArray->getKeyIndex($keyType);
1562: if ($otherIndex === null) {
1563: $optionalKeys[] = $i;
1564: continue;
1565: }
1566: if ($otherArray->isOptionalKey($otherIndex)) {
1567: $optionalKeys[] = $i;
1568: }
1569: $otherValueType = $otherArray->valueTypes[$otherIndex];
1570: $valueTypes[$i] = TypeCombinator::union($valueTypes[$i], $otherValueType);
1571: }
1572:
1573: $optionalKeys = array_values(array_unique($optionalKeys));
1574:
1575: $nextAutoIndexes = array_values(array_unique(array_merge($this->nextAutoIndexes, $otherArray->nextAutoIndexes)));
1576: sort($nextAutoIndexes);
1577:
1578: return new self($this->keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $this->isList->and($otherArray->isList));
1579: }
1580:
1581: /**
1582: * @param ConstantIntegerType|ConstantStringType $otherKeyType
1583: */
1584: private function getKeyIndex($otherKeyType): ?int
1585: {
1586: return self::findKeyIndex($otherKeyType, $this->keyTypes);
1587: }
1588:
1589: /**
1590: * @param ConstantIntegerType|ConstantStringType $otherKeyType
1591: * @param array<int, ConstantIntegerType|ConstantStringType> $keyTypes
1592: */
1593: private static function findKeyIndex($otherKeyType, array $keyTypes): ?int
1594: {
1595: foreach ($keyTypes as $i => $keyType) {
1596: if ($keyType->equals($otherKeyType)) {
1597: return $i;
1598: }
1599: }
1600:
1601: return null;
1602: }
1603:
1604: public function makeOffsetRequired(Type $offsetType): self
1605: {
1606: $offsetType = $offsetType->toArrayKey();
1607: $optionalKeys = $this->optionalKeys;
1608: foreach ($this->keyTypes as $i => $keyType) {
1609: if (!$keyType->equals($offsetType)) {
1610: continue;
1611: }
1612:
1613: foreach ($optionalKeys as $j => $key) {
1614: if ($i === $key) {
1615: unset($optionalKeys[$j]);
1616: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, array_values($optionalKeys), $this->isList);
1617: }
1618: }
1619:
1620: break;
1621: }
1622:
1623: return $this;
1624: }
1625:
1626: public function toPhpDocNode(): TypeNode
1627: {
1628: $items = [];
1629: $values = [];
1630: $exportValuesOnly = true;
1631: foreach ($this->keyTypes as $i => $keyType) {
1632: if ($keyType->getValue() !== $i) {
1633: $exportValuesOnly = false;
1634: }
1635: $keyPhpDocNode = $keyType->toPhpDocNode();
1636: if (!$keyPhpDocNode instanceof ConstTypeNode) {
1637: continue;
1638: }
1639: $valueType = $this->valueTypes[$i];
1640:
1641: /** @var ConstExprStringNode|ConstExprIntegerNode $keyNode */
1642: $keyNode = $keyPhpDocNode->constExpr;
1643: if ($keyNode instanceof ConstExprStringNode) {
1644: $value = $keyNode->value;
1645: if (self::isValidIdentifier($value)) {
1646: $keyNode = new IdentifierTypeNode($value);
1647: }
1648: }
1649:
1650: $isOptional = $this->isOptionalKey($i);
1651: if ($isOptional) {
1652: $exportValuesOnly = false;
1653: }
1654: $items[] = new ArrayShapeItemNode(
1655: $keyNode,
1656: $isOptional,
1657: $valueType->toPhpDocNode(),
1658: );
1659: $values[] = new ArrayShapeItemNode(
1660: null,
1661: $isOptional,
1662: $valueType->toPhpDocNode(),
1663: );
1664: }
1665:
1666: return new ArrayShapeNode($exportValuesOnly ? $values : $items);
1667: }
1668:
1669: public static function isValidIdentifier(string $value): bool
1670: {
1671: $result = Strings::match($value, '~^(?:[\\\\]?+[a-z_\\x80-\\xFF][0-9a-z_\\x80-\\xFF-]*+)++$~si');
1672:
1673: return $result !== null;
1674: }
1675:
1676: public function getFiniteTypes(): array
1677: {
1678: $arraysArraysForCombinations = [];
1679: $count = 0;
1680: foreach ($this->getAllArrays() as $array) {
1681: $values = $array->getValueTypes();
1682: $arraysForCombinations = [];
1683: $combinationCount = 1;
1684: foreach ($values as $valueType) {
1685: $finiteTypes = $valueType->getFiniteTypes();
1686: if ($finiteTypes === []) {
1687: return [];
1688: }
1689: $arraysForCombinations[] = $finiteTypes;
1690: $combinationCount *= count($finiteTypes);
1691: }
1692: $arraysArraysForCombinations[] = $arraysForCombinations;
1693: $count += $combinationCount;
1694: }
1695:
1696: if ($count > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1697: return [];
1698: }
1699:
1700: $finiteTypes = [];
1701: foreach ($arraysArraysForCombinations as $arraysForCombinations) {
1702: $combinations = CombinationsHelper::combinations($arraysForCombinations);
1703: foreach ($combinations as $combination) {
1704: $builder = ConstantArrayTypeBuilder::createEmpty();
1705: foreach ($combination as $i => $v) {
1706: $builder->setOffsetValueType($this->keyTypes[$i], $v);
1707: }
1708: $finiteTypes[] = $builder->getArray();
1709: }
1710: }
1711:
1712: return $finiteTypes;
1713: }
1714:
1715: /**
1716: * @param mixed[] $properties
1717: */
1718: public static function __set_state(array $properties): Type
1719: {
1720: return new self($properties['keyTypes'], $properties['valueTypes'], $properties['nextAutoIndexes'] ?? $properties['nextAutoIndex'], $properties['optionalKeys'] ?? [], $properties['isList'] ?? TrinaryLogic::createNo());
1721: }
1722:
1723: }
1724: