Skip to content

Commit

Permalink
[TypeDeclaration] Add Closure support on StrictArrayParamDimFetchRect…
Browse files Browse the repository at this point in the history
…or (#4632)
  • Loading branch information
samsonasik authored Aug 3, 2023
1 parent 36e88e1 commit 79953f6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\StrictArrayParamDimFetchRector\Fixture;

class WithClosure
{
public function resolve($item)
{
return function ($item) {
return $item['name'];
};
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\StrictArrayParamDimFetchRector\Fixture;

class WithClosure
{
public function resolve($item)
{
return function (array $item) {
return $item['name'];
};
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\AssignOp\Coalesce as AssignOpCoalesce;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Identifier;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PhpParser\NodeTraverser;
Expand Down Expand Up @@ -63,11 +66,11 @@ public function resolve(array $item)
*/
public function getNodeTypes(): array
{
return [ClassMethod::class, Function_::class];
return [ClassMethod::class, Function_::class, Closure::class];
}

/**
* @param ClassMethod|Function_ $node
* @param ClassMethod|Function_|Closure $node
*/
public function refactor(Node $node): ?Node
{
Expand Down Expand Up @@ -97,15 +100,23 @@ public function refactor(Node $node): ?Node
return null;
}

private function isParamAccessedArrayDimFetch(Param $param, ClassMethod|Function_ $functionLike): bool
private function isParamAccessedArrayDimFetch(Param $param, ClassMethod|Function_|Closure $functionLike): bool
{
if ($functionLike->stmts === null) {
return false;
}

$paramName = $this->getName($param);

$isParamAccessedArrayDimFetch = false;
$this->traverseNodesWithCallable($functionLike, function (Node $node) use (
$this->traverseNodesWithCallable($functionLike->stmts, function (Node $node) use (
$paramName,
&$isParamAccessedArrayDimFetch,
): int|null {
if ($node instanceof Class_ || $node instanceof FunctionLike) {
return NodeTraverser::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}

if ($this->shouldStop($node, $paramName)) {
// force set to false to avoid too early replaced
$isParamAccessedArrayDimFetch = false;
Expand Down

0 comments on commit 79953f6

Please sign in to comment.