Skip to content

Commit 69197d1

Browse files
authored
[TypeDeclaration] Allow named arg on AddArrayFunctionClosureParamTypeRector (#7397)
1 parent 66c3294 commit 69197d1

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\FuncCall\AddArrayFunctionClosureParamTypeRector\Fixture;
4+
5+
final class WithNamedArg
6+
{
7+
public function run()
8+
{
9+
$array = [1, 2, 3];
10+
$result = array_filter(callback: fn ($item) => $item * 2, array: $array);
11+
}
12+
}
13+
14+
?>
15+
-----
16+
<?php
17+
18+
namespace Rector\Tests\TypeDeclaration\Rector\FuncCall\AddArrayFunctionClosureParamTypeRector\Fixture;
19+
20+
final class WithNamedArg
21+
{
22+
public function run()
23+
{
24+
$array = [1, 2, 3];
25+
$result = array_filter(callback: fn (int $item) => $item * 2, array: $array);
26+
}
27+
}
28+
29+
?>

rules/TypeDeclaration/Rector/FuncCall/AddArrayFunctionClosureParamTypeRector.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Rector\TypeDeclaration\Rector\FuncCall;
66

77
use PhpParser\Node;
8+
use PhpParser\Node\Arg;
89
use PhpParser\Node\Expr\ArrowFunction;
910
use PhpParser\Node\Expr\Closure;
1011
use PhpParser\Node\Expr\FuncCall;
@@ -86,25 +87,34 @@ public function refactor(Node $node): ?Node
8687
$arrayPosition = $positions['array'];
8788
$callbackPosition = $positions['callback'];
8889

89-
$firstArgExpr = $node->getArgs()[$callbackPosition]
90-
->value;
91-
if (! $firstArgExpr instanceof ArrowFunction && ! $firstArgExpr instanceof Closure) {
90+
$callbackArg = $node->getArg('callback', $callbackPosition);
91+
if (! $callbackArg instanceof Arg) {
9292
continue;
9393
}
9494

95-
if (count($firstArgExpr->getParams()) !== 1) {
95+
$callbackArgExpr = $callbackArg->value;
96+
if (! $callbackArgExpr instanceof ArrowFunction && ! $callbackArgExpr instanceof Closure) {
9697
continue;
9798
}
9899

99-
$arrowFunction = $firstArgExpr;
100+
if (count($callbackArgExpr->getParams()) !== 1) {
101+
continue;
102+
}
103+
104+
$arrowFunction = $callbackArgExpr;
100105
$arrowFunctionParam = $arrowFunction->getParams()[0];
101106

102107
// param is known already
103108
if ($arrowFunctionParam->type instanceof Node) {
104109
continue;
105110
}
106111

107-
$passedExprType = $this->getType($node->getArgs()[$arrayPosition]->value);
112+
$arrayArg = $node->getArg('array', $arrayPosition);
113+
if (! $arrayArg instanceof Arg) {
114+
continue;
115+
}
116+
117+
$passedExprType = $this->getType($arrayArg->value);
108118

109119
$singlePassedExprType = $this->resolveArrayItemType($passedExprType);
110120
if (! $singlePassedExprType instanceof Type) {

0 commit comments

Comments
 (0)