Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CodeQuality] FuncLikeToFirstClassCallableRector #6667

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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,48 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo)
{
return FooBar::foo($foo);
};

fn ($foo) => FooBar::foo($foo);

$bar = null;

fn ($foo) => $bar->foo($foo);

function ($foo) use ($bar)
{
return $bar->foo($foo);
};

function ($foo, $bar, $ray)
{
return FooBar::foo($foo, $bar);
};

fn ($foo, $bar, $ray) => FooBar::foo($foo);

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

FooBar::foo(...);

FooBar::foo(...);

$bar = null;

$bar->foo(...);

$bar->foo(...);

FooBar::foo(...);

FooBar::foo(...);

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo)
{
return $foo->foo();
};

function ($foo)
{
return (new $foo)->foo();
};

fn ($foo) => $foo->foo();

function ($foo)
{
return $foo::foo();
};

function ($foo)
{
return ($foo . '\\Foo')::foo();
};

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo)
{
FooBar::foo($foo);
};

$bar = null;

function ($foo) use ($bar)
{
$bar->foo($foo);
};

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo)
{
$foo = 1;
return FooBar::foo($foo);
};

fn ($foo) => FooBar::foo($foo) && true;

$bar = null;

function ($foo) use ($bar)
{
$foo = 1;
return $bar->foo($foo);
};

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo)
{
return $foo;
};

fn ($foo) => $foo;

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function ($foo, $bar)
{
return FooBar::foo($bar, $foo);
};

fn ($foo, $bar) => FooBar::foo($bar, $foo);

$bar = null;

fn ($foo, $bar) => $bar->foo($bar, $foo);

function ($foo, $barFoo) use ($bar)
{
return $bar->foo($barFoo, $foo);
};

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

function (...$foo)
{
return FooBar::foo(...$foo);
};

fn (...$foo) => FooBar::foo(...$foo);

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\Fixture;

FooBar::foo(...);

FooBar::foo(...);

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class FuncLikeToFirstClassCallableRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector;
use Rector\Config\RectorConfig;

return RectorConfig::configure()
->withRules([FuncLikeToFirstClassCallableRector::class]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\FunctionLike;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\VariadicPlaceholder;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;

/**
* @see \Rector\Tests\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector\FuncLikeToFirstClassCallableRectorTest
*/
final class FuncLikeToFirstClassCallableRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'converts function like to first class callable',
[New CodeSample(
<<<'CODE_SAMPLE'
function ($parameter) { return Call::to($parameter); }
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
Call::to(...);
CODE_SAMPLE
,
)]
);
}

public function getNodeTypes(): array
{
return [ArrowFunction::class, Closure::class];
}

/**
* @param ArrowFunction|Closure $node
*/
public function refactor(Node $node): null|StaticCall|MethodCall
{
$extractedMethodCall = $this->extractMethodCallFromFuncLike($node);

if (! $extractedMethodCall instanceof MethodCall && ! $extractedMethodCall instanceof StaticCall) {
return null;
}

if ($extractedMethodCall instanceof MethodCall) {
return new MethodCall($extractedMethodCall->var, $extractedMethodCall->name, [new VariadicPlaceholder()]);
}

return new StaticCall($extractedMethodCall->class, $extractedMethodCall->name, [new VariadicPlaceholder()]);
}

private function extractMethodCallFromFuncLike(Closure|ArrowFunction $node): MethodCall|StaticCall|null
{
if ($node instanceof ArrowFunction) {
if (
($node->expr instanceof MethodCall || $node->expr instanceof StaticCall) &&
! $node->expr->isFirstClassCallable() &&
$this->sameParamsForArgs($node->getParams(), $node->expr->getArgs()) &&
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is named argument need to be skipped as well ?

$this->isNonDependantMethod($node->expr, $node->getParams())
) {
return $node->expr;
}

return null;
}

if (count($node->stmts) != 1 || ! $node->getStmts()[0] instanceof Return_) {
return null;
}

$callLike = $node->getStmts()[0]
->expr;

if (! $callLike instanceof MethodCall && ! $callLike instanceof StaticCall) {
return null;
}

if (
! $callLike->isFirstClassCallable() &&
$this->sameParamsForArgs($node->getParams(), $callLike->getArgs()) &&
$this->isNonDependantMethod($callLike, $node->getParams())) {
return $callLike;
}

return null;
}

/**
* @param Node\Param[] $params
* @param Node\Arg[] $args
*/
private function sameParamsForArgs(array $params, array $args): bool
{
Assert::allIsInstanceOf($args, Arg::class);
Assert::allIsInstanceOf($params, Param::class);

if (count($args) > count($params)) {
return false;
}

if (count($args) === 1 && $args[0]->unpack) {
return $params[0]->variadic;
}

foreach ($args as $key => $arg) {
if (! $this->nodeComparator->areNodesEqual($arg->value, $params[$key]->var)) {
return false;
}
}

return true;
}

/**
* Makes sure the parameter isn't used to make the call e.g. in the var or class
*
* @param Param[] $params
*/
private function isNonDependantMethod(StaticCall|MethodCall $expr, array $params): bool
{
Assert::allIsInstanceOf($params, Param::class);

$found = false;

foreach ($params as $param) {
if ($expr instanceof MethodCall) {
$this->traverseNodesWithCallable($expr->var, function (Node $node) use ($param, &$found): null {
if ($this->nodeComparator->areNodesEqual($node, $param->var)) {
$found = true;
}

return null;
});
}
if ($expr instanceof StaticCall) {
$this->traverseNodesWithCallable($expr->class, function (Node $node) use ($param, &$found): null {
if ($this->nodeComparator->areNodesEqual($node, $param->var)) {
$found = true;
}

return null;
});
}

if ($found) {
return false;
}
}

return true;
}
}
2 changes: 2 additions & 0 deletions src/Config/Level/CodeQualityLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector;
use Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector;
use Rector\CodeQuality\Rector\FuncCall\UnwrapSprintfOneArgumentRector;
use Rector\CodeQuality\Rector\FunctionLike\FuncLikeToFirstClassCallableRector;
use Rector\CodeQuality\Rector\Identical\BooleanNotIdenticalToNotIdenticalRector;
use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector;
use Rector\CodeQuality\Rector\Identical\SimplifyArraySearchRector;
Expand Down Expand Up @@ -175,6 +176,7 @@ final class CodeQualityLevel
CompleteMissingIfElseBracketRector::class,
RemoveUselessIsObjectCheckRector::class,
StaticToSelfStaticMethodCallOnFinalClassRector::class,
FuncLikeToFirstClassCallableRector::class,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same like FunctionFirstClassCallableRector https://getrector.com/rule-detail/function-first-class-callable-rector

it should not part of any set, as imo, it is by preference.

];

/**
Expand Down
Loading
Loading