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

namespace Rector\Tests\Php81\Rector\Array_\FirstClassCallableRector\Fixture;

final class SomeClassWithOwnPrivate
{
public function run()
{
$name = [$this, 'name'];
}

private function name()
{
}
}

?>
-----
<?php

namespace Rector\Tests\Php81\Rector\Array_\FirstClassCallableRector\Fixture;

final class SomeClassWithOwnPrivate
{
public function run()
{
$name = $this->name(...);
}

private function name()
{
}
}

?>
32 changes: 25 additions & 7 deletions rules/Php81/Rector/Array_/ArrayToFirstClassCallableRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public function name()
}
}
CODE_SAMPLE
,
),
]);
}
Expand Down Expand Up @@ -123,7 +124,7 @@ public function refactor(Node $node): StaticCall|MethodCall|null
if ($type instanceof FullyQualifiedObjectType && $this->isNonStaticOtherObject(
$type,
$arrayCallable,
$scope
$scope,
)) {
return null;
}
Expand All @@ -133,13 +134,9 @@ public function refactor(Node $node): StaticCall|MethodCall|null

$methodName = $arrayCallable->getMethod();
$methodCall = new MethodCall($callerExpr, $methodName, $args);
$classReflection = $this->reflectionResolver->resolveClassReflectionSourceObject($methodCall);

if ($classReflection instanceof ClassReflection && $classReflection->hasNativeMethod($methodName)) {
$method = $classReflection->getNativeMethod($methodName);
if (! $method->isPublic()) {
return null;
}
if ($this->isReferenceToNonPublicMethodOutsideOwningScope($methodCall, $methodName)) {
return null;
}

return $methodCall;
Expand Down Expand Up @@ -174,4 +171,25 @@ private function isNonStaticOtherObject(

return ! $extendedMethodReflection->isPublic();
}

private function isReferenceToNonPublicMethodOutsideOwningScope(MethodCall $methodCall, string $methodName): bool
{
if ($methodCall->var instanceof Variable && $methodCall->var->name === 'this') {
// If the callable is scoped to `$this` then it can be converted even if it is protected / private
return false;
}

// If the callable is scoped to another object / variable then it should only be converted if it is public
// https://github.com/rectorphp/rector/issues/8659
$classReflection = $this->reflectionResolver->resolveClassReflectionSourceObject($methodCall);

if ($classReflection instanceof ClassReflection && $classReflection->hasNativeMethod($methodName)) {
$method = $classReflection->getNativeMethod($methodName);
if (! $method->isPublic()) {
return true;
}
}

return false;
}
}