Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Rector\Tests\CodingStyle\Rector\FunctionLike\FunctionLikeToFirstClassCallableRector\Fixture;

function makeInstance(string $className, array $options = []): object
{
return new $className(...$options);
}

// This works - closure ignores the key (2nd parameter from array_map)
$result1 = array_map(
static fn(string $className): object => makeInstance($className),
$items
);

// This FAILS - first-class callable receives BOTH value and key
// array_map passes: $className (string) and $key (int)
// But makeInstance expects: $className (string) and $options (array)
$result2 = array_map(makeInstance(...), $items, array_keys($items));
// TypeError: makeInstance(): Argument #2 ($options) must be of type array, int give
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Identifier;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\VariadicPlaceholder;
use PhpParser\NodeVisitor;
use PHPStan\Analyser\Scope;
use Rector\PhpParser\AstResolver;
use Rector\PHPStan\ScopeFetcher;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
Expand All @@ -31,6 +33,11 @@
*/
final class FunctionLikeToFirstClassCallableRector extends AbstractRector implements MinPhpVersionInterface
{
public function __construct(
private readonly AstResolver $astResolver
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
Expand Down Expand Up @@ -111,7 +118,16 @@ private function shouldSkip(
return true;
}

return $this->isUsingThisInNonObjectContext($callLike, $scope);
if ($this->isUsingThisInNonObjectContext($callLike, $scope)) {
return true;
}

$functionLike = $this->astResolver->resolveClassMethodOrFunctionFromCall($callLike);
if (! $functionLike instanceof FunctionLike) {
return false;
}

return count($functionLike->getParams()) > 1;
}

private function extractCallLike(Closure|ArrowFunction $node): FuncCall|MethodCall|StaticCall|null
Expand Down