1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use PhpParser\Node as PhpParserNode;
6: use PhpParser\Node\Arg;
7: use PhpParser\Node\Expr\Array_;
8: use PhpParser\Node\Expr\FuncCall;
9: use PhpParser\Node\Expr\MethodCall;
10: use PhpParser\Node\Expr\New_;
11: use PhpParser\Node\Expr\StaticCall;
12: use PhpParser\Node\Identifier;
13: use PhpParser\Node\Scalar\Int_;
14: use PhpParser\Node\Scalar\String_;
15: use PHPStan\Node\Expr\TypeExpr;
16: use PHPStan\Node\Printer\ExprPrinter;
17: use PHPStan\Reflection\ParametersAcceptor;
18: use PHPStan\Reflection\ParametersAcceptorSelector;
19: use PHPStan\TrinaryLogic;
20: use PHPStan\Turbo\ShadowedByTurboExtension;
21: use PHPStan\Type\Constant\ConstantArrayType;
22: use function array_is_list;
23: use function array_key_exists;
24: use function array_keys;
25: use function array_values;
26: use function count;
27: use function is_string;
28: use function key;
29: use function ksort;
30: use function max;
31:
32: /**
33: * @api
34: */
35: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ArgumentsNormalizer.cpp')]
36: final class ArgumentsNormalizer
37: {
38:
39: public const ORIGINAL_ARG_ATTRIBUTE = 'originalArg';
40:
41: /**
42: * @return array{ParametersAcceptor, FuncCall, TrinaryLogic}|null
43: */
44: public static function reorderCallUserFuncArguments(
45: FuncCall $callUserFuncCall,
46: Scope $scope,
47: ): ?array
48: {
49: $args = $callUserFuncCall->getArgs();
50: if (count($args) < 1) {
51: return null;
52: }
53:
54: $passThruArgs = [];
55: $callbackArg = null;
56: foreach ($args as $i => $arg) {
57: if ($callbackArg === null) {
58: if ($arg->name === null && $i === 0) {
59: $callbackArg = $arg;
60: continue;
61: }
62: if ($arg->name !== null && $arg->name->toString() === 'callback') {
63: $callbackArg = $arg;
64: continue;
65: }
66: }
67:
68: $passThruArgs[] = $arg;
69: }
70:
71: if ($callbackArg === null) {
72: return null;
73: }
74:
75: $calledOnType = $scope->getType($callbackArg->value);
76: if (!$calledOnType->isCallable()->yes()) {
77: return null;
78: }
79:
80: $callableParametersAcceptors = $calledOnType->getCallableParametersAcceptors($scope);
81: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
82: $scope,
83: $passThruArgs,
84: $callableParametersAcceptors,
85: null,
86: );
87:
88: $acceptsNamedArguments = TrinaryLogic::createYes();
89: foreach ($callableParametersAcceptors as $callableParametersAcceptor) {
90: $acceptsNamedArguments = $acceptsNamedArguments->and($callableParametersAcceptor->acceptsNamedArguments());
91: }
92:
93: return [$parametersAcceptor, new FuncCall(
94: $callbackArg->value,
95: $passThruArgs,
96: self::attributesWithoutPrintedForm($callUserFuncCall),
97: ), $acceptsNamedArguments];
98: }
99:
100: /**
101: * @return array{ParametersAcceptor, FuncCall, TrinaryLogic}|null
102: */
103: public static function reorderCallUserFuncArrayArguments(
104: FuncCall $callUserFuncArrayCall,
105: Scope $scope,
106: ): ?array
107: {
108: $args = $callUserFuncArrayCall->getArgs();
109: if (count($args) < 2) {
110: return null;
111: }
112:
113: $callbackArg = null;
114: $argsArrayArg = null;
115: foreach ($args as $i => $arg) {
116: if ($callbackArg === null) {
117: if ($arg->name === null && $i === 0) {
118: $callbackArg = $arg;
119: continue;
120: }
121: if ($arg->name !== null && $arg->name->toString() === 'callback') {
122: $callbackArg = $arg;
123: continue;
124: }
125: }
126:
127: if ($argsArrayArg !== null) {
128: continue;
129: }
130: if ($arg->name === null && $i === 1) {
131: $argsArrayArg = $arg;
132: continue;
133: }
134: if ($arg->name === null || $arg->name->toString() !== 'args') {
135: continue;
136: }
137: $argsArrayArg = $arg;
138: }
139:
140: if ($callbackArg === null || $argsArrayArg === null) {
141: return null;
142: }
143:
144: if (!$argsArrayArg->value instanceof Array_) {
145: return null;
146: }
147:
148: $passThruArgs = [];
149: foreach ($argsArrayArg->value->items as $item) {
150: $key = null;
151: if ($item->key instanceof String_) {
152: /** @var int|string $key */
153: $key = key([$item->key->value => null]);
154: if ($key === '') {
155: return null;
156: }
157: } elseif ($item->key !== null && !$item->key instanceof Int_) {
158: // Dynamic key, we cannot be sure.
159: return null;
160: }
161:
162: $passThruArgs[] = new Arg(
163: $item->value,
164: $item->byRef,
165: $item->unpack,
166: self::attributesWithoutPrintedForm($item),
167: is_string($key) ? new Identifier($key) : null,
168: );
169: }
170:
171: $calledOnType = $scope->getType($callbackArg->value);
172: if (!$calledOnType->isCallable()->yes()) {
173: return null;
174: }
175:
176: $callableParametersAcceptors = $calledOnType->getCallableParametersAcceptors($scope);
177: $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
178: $scope,
179: $passThruArgs,
180: $callableParametersAcceptors,
181: null,
182: );
183:
184: $acceptsNamedArguments = TrinaryLogic::createYes();
185: foreach ($callableParametersAcceptors as $callableParametersAcceptor) {
186: $acceptsNamedArguments = $acceptsNamedArguments->and($callableParametersAcceptor->acceptsNamedArguments());
187: }
188:
189: return [$parametersAcceptor, new FuncCall(
190: $callbackArg->value,
191: $passThruArgs,
192: self::attributesWithoutPrintedForm($callUserFuncArrayCall),
193: ), $acceptsNamedArguments];
194: }
195:
196: public static function reorderFuncArguments(
197: ParametersAcceptor $parametersAcceptor,
198: FuncCall $functionCall,
199: ): ?FuncCall
200: {
201: $args = $functionCall->getArgs();
202: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
203:
204: if ($reorderedArgs === null) {
205: return null;
206: }
207:
208: // return identical object if not reordered, as TypeSpecifier relies on object identity
209: if ($reorderedArgs === $args) {
210: return $functionCall;
211: }
212:
213: return new FuncCall(
214: $functionCall->name,
215: $reorderedArgs,
216: self::attributesWithoutPrintedForm($functionCall),
217: );
218: }
219:
220: public static function reorderMethodArguments(
221: ParametersAcceptor $parametersAcceptor,
222: MethodCall $methodCall,
223: ): ?MethodCall
224: {
225: $args = $methodCall->getArgs();
226: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
227:
228: if ($reorderedArgs === null) {
229: return null;
230: }
231:
232: // return identical object if not reordered, as TypeSpecifier relies on object identity
233: if ($reorderedArgs === $args) {
234: return $methodCall;
235: }
236:
237: return new MethodCall(
238: $methodCall->var,
239: $methodCall->name,
240: $reorderedArgs,
241: self::attributesWithoutPrintedForm($methodCall),
242: );
243: }
244:
245: public static function reorderStaticCallArguments(
246: ParametersAcceptor $parametersAcceptor,
247: StaticCall $staticCall,
248: ): ?StaticCall
249: {
250: $args = $staticCall->getArgs();
251: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
252:
253: if ($reorderedArgs === null) {
254: return null;
255: }
256:
257: // return identical object if not reordered, as TypeSpecifier relies on object identity
258: if ($reorderedArgs === $args) {
259: return $staticCall;
260: }
261:
262: return new StaticCall(
263: $staticCall->class,
264: $staticCall->name,
265: $reorderedArgs,
266: self::attributesWithoutPrintedForm($staticCall),
267: );
268: }
269:
270: public static function reorderNewArguments(
271: ParametersAcceptor $parametersAcceptor,
272: New_ $new,
273: ): ?New_
274: {
275: $args = $new->getArgs();
276: $reorderedArgs = self::reorderArgs($parametersAcceptor, $args);
277:
278: if ($reorderedArgs === null) {
279: return null;
280: }
281:
282: // return identical object if not reordered, as TypeSpecifier relies on object identity
283: if ($reorderedArgs === $args) {
284: return $new;
285: }
286:
287: return new New_(
288: $new->class,
289: $reorderedArgs,
290: self::attributesWithoutPrintedForm($new),
291: );
292: }
293:
294: /**
295: * The argument bound to the parameter at $position named $name: the
296: * positional argument at that index or the one passed by that name.
297: *
298: * This method can be useful in simple cases when no reflection is needed.
299: * In more complex cases where reflection information is available,
300: * use ParametersAcceptorSelector::selectFromArgs() and ArgumentsNormalizer::reorder*Arguments() instead.
301: *
302: * @param Arg[] $args
303: * @param 0|positive-int $position
304: * @param non-empty-string $name
305: */
306: public static function getArgByPositionOrName(array $args, int $position, string $name): ?Arg
307: {
308: foreach ($args as $i => $arg) {
309: if ($arg->name === null ? $i === $position : $arg->name->toString() === $name) {
310: return $arg;
311: }
312: }
313:
314: return null;
315: }
316:
317: /**
318: * @param Arg[] $callArgs
319: * @return ?list<Arg>
320: */
321: public static function reorderArgs(ParametersAcceptor $parametersAcceptor, array $callArgs): ?array
322: {
323: if (count($callArgs) === 0) {
324: return [];
325: }
326:
327: $hasNamedArgs = false;
328: foreach ($callArgs as $arg) {
329: if ($arg->name !== null) {
330: $hasNamedArgs = true;
331: break;
332: }
333: }
334: if (!$hasNamedArgs) {
335: return array_values($callArgs);
336: }
337:
338: foreach ($callArgs as $arg) {
339: if ($arg->unpack) {
340: // the number of parameters an unpacked argument fills is unknown here,
341: // so the positions of the named arguments that follow it cannot be determined
342: return null;
343: }
344: }
345:
346: $hasVariadic = false;
347: $argumentPositions = [];
348: $signatureParameters = $parametersAcceptor->getParameters();
349: foreach ($signatureParameters as $i => $parameter) {
350: if ($hasVariadic) {
351: // variadic parameter must be last
352: return null;
353: }
354:
355: $hasVariadic = $parameter->isVariadic();
356: $argumentPositions[$parameter->getName()] = $i;
357: }
358:
359: $reorderedArgs = [];
360: $additionalNamedArgs = [];
361: $appendArgs = [];
362: foreach ($callArgs as $i => $arg) {
363: if ($arg->name === null) {
364: // add regular args as is
365:
366: $attributes = $arg->getAttributes();
367: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
368: $reorderedArgs[$i] = new Arg(
369: $arg->value,
370: $arg->byRef,
371: $arg->unpack,
372: $attributes,
373: null,
374: );
375: } elseif (array_key_exists($arg->name->toString(), $argumentPositions)) {
376: $argName = $arg->name->toString();
377: // order named args into the position the signature expects them
378: $attributes = $arg->getAttributes();
379: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
380: if (array_key_exists($argumentPositions[$argName], $reorderedArgs)) {
381: continue;
382: }
383: $reorderedArgs[$argumentPositions[$argName]] = new Arg(
384: $arg->value,
385: $arg->byRef,
386: $arg->unpack,
387: $attributes,
388: null,
389: );
390: } else {
391: if (!$hasVariadic) {
392: $attributes = $arg->getAttributes();
393: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
394: $appendArgs[] = new Arg(
395: $arg->value,
396: $arg->byRef,
397: $arg->unpack,
398: $attributes,
399: null,
400: );
401: continue;
402: }
403:
404: $attributes = $arg->getAttributes();
405: $attributes[self::ORIGINAL_ARG_ATTRIBUTE] = $arg;
406: $additionalNamedArgs[] = new Arg(
407: $arg->value,
408: $arg->byRef,
409: $arg->unpack,
410: $attributes,
411: null,
412: );
413: }
414: }
415:
416: // replace variadic parameter with additional named args, except if it is already set
417: $additionalNamedArgsOffset = count($argumentPositions) - 1;
418: if (array_key_exists($additionalNamedArgsOffset, $reorderedArgs)) {
419: $additionalNamedArgsOffset++;
420: }
421:
422: foreach ($additionalNamedArgs as $i => $additionalNamedArg) {
423: $reorderedArgs[$additionalNamedArgsOffset + $i] = $additionalNamedArg;
424: }
425:
426: if (count($reorderedArgs) === 0) {
427: foreach ($appendArgs as $arg) {
428: $reorderedArgs[] = $arg;
429: }
430: return $reorderedArgs;
431: }
432:
433: // fill up all holes with default values until the last given argument
434: for ($j = 0; $j < max(array_keys($reorderedArgs)); $j++) {
435: if (array_key_exists($j, $reorderedArgs)) {
436: continue;
437: }
438: if (!array_key_exists($j, $signatureParameters)) {
439: return null;
440: }
441:
442: $parameter = $signatureParameters[$j];
443:
444: // we can only fill up optional parameters with default values
445: if (!$parameter->isOptional()) {
446: return null;
447: }
448:
449: $defaultValue = $parameter->getDefaultValue();
450: if ($defaultValue === null) {
451: if (!$parameter->isVariadic()) {
452: // like an optional parameter combined from variants that do not all have it
453: return null;
454: }
455: $defaultValue = new ConstantArrayType([], []);
456: }
457:
458: $reorderedArgs[$j] = new Arg(
459: new TypeExpr($defaultValue),
460: );
461: }
462:
463: ksort($reorderedArgs);
464:
465: foreach ($appendArgs as $arg) {
466: $reorderedArgs[] = $arg;
467: }
468:
469: if (!array_is_list($reorderedArgs)) {
470: $reorderedArgs = array_values($reorderedArgs);
471: }
472:
473: return $reorderedArgs;
474: }
475:
476: /**
477: * The printed form of an expression is derived from its own arguments, so
478: * it must not travel to a node whose arguments were just reordered — the
479: * normalized call would report the original's expression key, named
480: * arguments and all.
481: *
482: * @return array<string, mixed>
483: */
484: private static function attributesWithoutPrintedForm(PhpParserNode $node): array
485: {
486: $attributes = $node->getAttributes();
487: unset($attributes[ExprPrinter::ATTRIBUTE_CACHE_KEY]);
488:
489: return $attributes;
490: }
491:
492: }
493: