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,22 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Class_\InnerFunctionToPrivateMethodRector\Fixture;

class SkipStringCallable
{
public static function getOptions()
{
function sortByOrder(array $a, array $b): int
{
return strcmp((string) $a['label'], (string) $b['label']);
}

$options = [
['value' => 'b', 'label' => 'Bravo'],
['value' => 'a', 'label' => 'Alpha'],
];

usort($options, 'sortByOrder');
return $options;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
Expand Down Expand Up @@ -133,6 +134,11 @@ private function extractInnerFunctions(ClassMethod $classMethod, array &$existin
continue;
}

// avoid breaking string callables, e.g. usort($items, 'functionName')
if ($this->isReferencedAsStringCallable($classMethod, $functionName)) {
continue;
}

$existingMethodNames[] = $functionName;
$innerFunctions[] = $stmt;
unset($classMethod->stmts[$key]);
Expand All @@ -145,6 +151,24 @@ private function extractInnerFunctions(ClassMethod $classMethod, array &$existin
return $innerFunctions;
}

private function isReferencedAsStringCallable(ClassMethod $classMethod, string $functionName): bool
{
$isReferenced = false;

$this->traverseNodesWithCallable($classMethod->stmts ?? [], function (Node $node) use (
$functionName,
&$isReferenced
): null {
if ($node instanceof String_ && $node->value === $functionName) {
$isReferenced = true;
}

return null;
});

return $isReferenced;
}

private function createPrivateMethod(Function_ $innerFunction, bool $isStatic): ClassMethod
{
$flags = Modifiers::PRIVATE;
Expand Down
Loading