Skip to content

Commit ca5155c

Browse files
authored
[CodeQuality] Skip inner function referenced as string callable in InnerFunctionToPrivateMethodRector (#8154)
1 parent cfea3ba commit ca5155c

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Class_\InnerFunctionToPrivateMethodRector\Fixture;
4+
5+
class SkipStringCallable
6+
{
7+
public static function getOptions()
8+
{
9+
function sortByOrder(array $a, array $b): int
10+
{
11+
return strcmp((string) $a['label'], (string) $b['label']);
12+
}
13+
14+
$options = [
15+
['value' => 'b', 'label' => 'Bravo'],
16+
['value' => 'a', 'label' => 'Alpha'],
17+
];
18+
19+
usort($options, 'sortByOrder');
20+
return $options;
21+
}
22+
}

‎rules/CodeQuality/Rector/Class_/InnerFunctionToPrivateMethodRector.php‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use PhpParser\Node\Expr\StaticCall;
1212
use PhpParser\Node\Expr\Variable;
1313
use PhpParser\Node\Name;
14+
use PhpParser\Node\Scalar\String_;
1415
use PhpParser\Node\Stmt\Class_;
1516
use PhpParser\Node\Stmt\ClassMethod;
1617
use PhpParser\Node\Stmt\Function_;
@@ -133,6 +134,11 @@ private function extractInnerFunctions(ClassMethod $classMethod, array &$existin
133134
continue;
134135
}
135136

137+
// avoid breaking string callables, e.g. usort($items, 'functionName')
138+
if ($this->isReferencedAsStringCallable($classMethod, $functionName)) {
139+
continue;
140+
}
141+
136142
$existingMethodNames[] = $functionName;
137143
$innerFunctions[] = $stmt;
138144
unset($classMethod->stmts[$key]);
@@ -145,6 +151,24 @@ private function extractInnerFunctions(ClassMethod $classMethod, array &$existin
145151
return $innerFunctions;
146152
}
147153

154+
private function isReferencedAsStringCallable(ClassMethod $classMethod, string $functionName): bool
155+
{
156+
$isReferenced = false;
157+
158+
$this->traverseNodesWithCallable($classMethod->stmts ?? [], function (Node $node) use (
159+
$functionName,
160+
&$isReferenced
161+
): null {
162+
if ($node instanceof String_ && $node->value === $functionName) {
163+
$isReferenced = true;
164+
}
165+
166+
return null;
167+
});
168+
169+
return $isReferenced;
170+
}
171+
148172
private function createPrivateMethod(Function_ $innerFunction, bool $isStatic): ClassMethod
149173
{
150174
$flags = Modifiers::PRIVATE;

0 commit comments

Comments
 (0)