Skip to content

Commit

Permalink
[CodeQuality] Handle CallableThisArrayToAnonymousFunctionRector on st…
Browse files Browse the repository at this point in the history
…atic call (#382)

* Add failing test fixture for CallableThisArrayToAnonymousFunctionRector

# Failing Test for CallableThisArrayToAnonymousFunctionRector

Based on https://getrector.org/demo/1ebdd568-53a1-6744-871e-eb16ad5fe7b4

* Closes #381

* phpstan

Co-authored-by: Zing <zingimmick@outlook.com>
  • Loading branch information
samsonasik and zingimmick committed Jul 5, 2021
1 parent ff1ad31 commit c0d6760
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector\Fixture;

final class StaticCall
{
public function run(array $values)
{
usort($values, [StaticCall::class, 'compareSize']);

return $values;
}

private static function compareSize(int $first, $second): bool
{
return $first <=> $second;
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector\Fixture;

final class StaticCall
{
public function run(array $values)
{
usort($values, function (int $first, $second) : bool {
return StaticCall::compareSize($first, $second);
});

return $values;
}

private static function compareSize(int $first, $second): bool
{
return $first <=> $second;
}
}

?>
12 changes: 11 additions & 1 deletion rules/Php72/NodeFactory/AnonymousFunctionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
use Rector\PHPStanStaticTypeMapper\ValueObject\TypeKind;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\StaticCall;

final class AnonymousFunctionFactory
{
Expand Down Expand Up @@ -93,7 +95,15 @@ public function createFromPhpMethodReflection(PhpMethodReflection $phpMethodRefl

$anonymousFunction->params = $newParams;

$innerMethodCall = new MethodCall($expr, $phpMethodReflection->getName());
if ($expr instanceof ClassConstFetch && $expr->name instanceof Identifier && $this->nodeNameResolver->isName($expr->name, 'class')) {
/** @var Expr $expr */
$expr = $expr->class;
}

$innerMethodCall = $phpMethodReflection->isStatic()
? new StaticCall($expr, $phpMethodReflection->getName())
: new MethodCall($expr, $phpMethodReflection->getName());

$innerMethodCall->args = $this->nodeFactory->createArgsFromParams($newParams);

if (! $functionVariantWithPhpDoc->getReturnType() instanceof MixedType) {
Expand Down

0 comments on commit c0d6760

Please sign in to comment.