3737final class ArrayMapFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
3838{
3939
40+ /** The largest number of array lists that unpacked list shapes can pass and that are mapped one by one */
41+ private const UNPACKED_ARRAY_LISTS_LIMIT = 16 ;
42+
4043 public function isFunctionSupported (FunctionReflection $ functionReflection ): bool
4144 {
4245 return $ functionReflection ->getName () === 'array_map ' ;
@@ -47,17 +50,134 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
4750 $ args = $ functionCall ->getArgs ();
4851 if (count ($ args ) >= 2 && in_array (true , array_map (static fn (Node \Arg $ arg ) => $ arg ->unpack , $ args ), true )) {
4952 $ arrayArgs = array_slice ($ args , 1 );
50- [$ arrayTypes , $ restType ] = UnpackedArgumentTypes ::expand (
51- array_map (static fn (Node \Arg $ arg ) => $ scope ->getType ($ arg ->value ), $ arrayArgs ),
52- array_map (static fn (Node \Arg $ arg ) => $ arg ->unpack , $ arrayArgs ),
53- );
53+ $ argTypes = array_map (static fn (Node \Arg $ arg ) => $ scope ->getType ($ arg ->value ), $ arrayArgs );
54+ $ unpacked = array_map (static fn (Node \Arg $ arg ) => $ arg ->unpack , $ arrayArgs );
55+
56+ $ arrayLists = self ::getUnpackedArrayLists ($ argTypes , $ unpacked );
57+ if ($ arrayLists !== null ) {
58+ $ requiredParametersCount = self ::getRequiredParametersCount ($ args [0 ]->value );
59+ $ types = [];
60+ foreach ($ arrayLists as $ arrayList ) {
61+ // PHP throws an ArgumentCountError when the callback gets fewer values than it requires
62+ if (count ($ arrayList ) < $ requiredParametersCount ) {
63+ continue ;
64+ }
65+
66+ $ type = $ this ->getTypeFromArgs ($ scope , [$ args [0 ], ...array_map (static fn (Type $ arrayType ) => new Node \Arg (new TypeExpr ($ arrayType )), $ arrayList )]);
67+ if ($ type === null ) {
68+ return null ;
69+ }
70+ $ types [] = $ type ;
71+ }
72+
73+ if ($ types === []) {
74+ return null ;
75+ }
76+
77+ return TypeCombinator ::union (...$ types );
78+ }
79+
80+ [$ arrayTypes , $ restType ] = UnpackedArgumentTypes ::expand ($ argTypes , $ unpacked );
5481 if ($ restType !== null ) {
5582 return self ::getTypeForUnknownArrayCount ($ scope , $ args [0 ]->value , $ arrayTypes , $ restType );
5683 }
5784
5885 $ args = [$ args [0 ], ...array_map (static fn (Type $ arrayType ) => new Node \Arg (new TypeExpr ($ arrayType )), $ arrayTypes )];
5986 }
6087
88+ return $ this ->getTypeFromArgs ($ scope , $ args );
89+ }
90+
91+ /**
92+ * Returns each list of arrays the args can pass, when every unpacked arg is
93+ * a union of list shapes, so that each list can be mapped as a known number
94+ * of arrays. Returns null when the number of arrays is not known.
95+ *
96+ * @param list<Type> $argTypes
97+ * @param list<bool> $unpacked
98+ * @return list<list<Type>>|null
99+ */
100+ private static function getUnpackedArrayLists (array $ argTypes , array $ unpacked ): ?array
101+ {
102+ $ arrayLists = [[]];
103+ foreach ($ argTypes as $ i => $ argType ) {
104+ $ choices = [[$ argType ]];
105+ if ($ unpacked [$ i ]) {
106+ $ constantArrays = $ argType ->getConstantArrays ();
107+ if ($ constantArrays === []) {
108+ return null ;
109+ }
110+
111+ $ choices = [];
112+ foreach ($ constantArrays as $ constantArray ) {
113+ foreach ($ constantArray ->getAllArrays () as $ array ) {
114+ if (!self ::hasPositionKeys ($ array )) {
115+ continue ;
116+ }
117+ $ choices [] = $ array ->getValueTypes ();
118+ }
119+ }
120+ if ($ choices === []) {
121+ return null ;
122+ }
123+ }
124+
125+ $ nextArrayLists = [];
126+ foreach ($ arrayLists as $ arrayList ) {
127+ foreach ($ choices as $ choice ) {
128+ $ nextArrayLists [] = [...$ arrayList , ...$ choice ];
129+ }
130+ }
131+ if (count ($ nextArrayLists ) > self ::UNPACKED_ARRAY_LISTS_LIMIT ) {
132+ return null ;
133+ }
134+ $ arrayLists = $ nextArrayLists ;
135+ }
136+
137+ return $ arrayLists ;
138+ }
139+
140+ /**
141+ * Whether the keys are 0, 1, 2 and so on. The optional keys of a list shape
142+ * also give arrays with a gap, which the list cannot be, and string keys
143+ * are passed as named args.
144+ */
145+ private static function hasPositionKeys (ConstantArrayType $ array ): bool
146+ {
147+ foreach ($ array ->getKeyTypes () as $ position => $ keyType ) {
148+ if ($ keyType ->getValue () !== $ position ) {
149+ return false ;
150+ }
151+ }
152+
153+ return true ;
154+ }
155+
156+ /**
157+ * The number of values a closure written in the call requires, 0 for other callbacks.
158+ */
159+ private static function getRequiredParametersCount (Node \Expr $ callback ): int
160+ {
161+ if (!$ callback instanceof Node \Expr \Closure && !$ callback instanceof Node \Expr \ArrowFunction) {
162+ return 0 ;
163+ }
164+
165+ $ count = 0 ;
166+ foreach ($ callback ->params as $ param ) {
167+ if ($ param ->default !== null || $ param ->variadic ) {
168+ break ;
169+ }
170+ $ count ++;
171+ }
172+
173+ return $ count ;
174+ }
175+
176+ /**
177+ * @param list<Node\Arg> $args
178+ */
179+ private function getTypeFromArgs (Scope $ scope , array $ args ): ?Type
180+ {
61181 $ numArgs = count ($ args );
62182 if ($ numArgs < 2 ) {
63183 return null ;
@@ -194,11 +314,38 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
194314 private static function getTypeForUnknownArrayCount (Scope $ scope , Node \Expr $ callback , array $ arrayTypes , Type $ restArrayType ): ?Type
195315 {
196316 $ callableType = $ scope ->getType ($ callback );
317+ [$ valueTypes , $ restValueType ] = ArrayMapCallbackParameterTypes ::getCallbackValueTypes ($ arrayTypes , $ restArrayType );
318+ if ($ callableType ->isNull ()->yes ()) {
319+ // One array is returned as it is, more arrays give a list with one value per array.
320+ // The type system cannot say how many general arrays there are, so assume more than one.
321+ $ tupleValueTypes = [];
322+ $ size = null ;
323+ $ addNull = false ;
324+ foreach ([...$ arrayTypes , $ restArrayType ] as $ arrayType ) {
325+ $ tupleValueTypes [] = $ arrayType ->getIterableValueType ();
326+ $ arraySizes = $ arrayType ->getArraySize ()->getConstantScalarValues ();
327+ if (count ($ arraySizes ) !== 1 || ($ size !== null && $ size !== $ arraySizes [0 ])) {
328+ $ addNull = true ;
329+ }
330+ $ size = $ arraySizes [0 ] ?? null ;
331+ }
332+ // as for a known number of arrays, null pads each array that can be shorter
333+ $ tupleValueType = TypeCombinator ::union (...$ tupleValueTypes );
334+ if ($ addNull ) {
335+ $ tupleValueType = TypeCombinator ::addNull ($ tupleValueType );
336+ }
337+ $ tupleType = TypeCombinator ::intersect (
338+ new ArrayType (IntegerRangeType ::createAllGreaterThanOrEqualTo (0 ), $ tupleValueType ),
339+ new AccessoryArrayListType (),
340+ new NonEmptyArrayType (),
341+ );
342+
343+ return TypeCombinator ::intersect (new ArrayType (IntegerRangeType ::createAllGreaterThanOrEqualTo (0 ), $ tupleType ), new AccessoryArrayListType ());
344+ }
197345 if (!$ callableType ->isCallable ()->yes ()) {
198346 return null ;
199347 }
200348
201- [$ valueTypes , $ restValueType ] = ArrayMapCallbackParameterTypes ::getCallbackValueTypes ($ arrayTypes , $ restArrayType );
202349 $ callArgs = [];
203350 foreach ($ valueTypes as $ valueType ) {
204351 $ callArgs [] = new Node \Arg (new TypeExpr ($ valueType ));
0 commit comments