Skip to content

Commit

Permalink
[Privatization] Skip parent class unknown on PrivatizeFinalClassMetho…
Browse files Browse the repository at this point in the history
…dRector (#4671)
  • Loading branch information
samsonasik authored Aug 6, 2023
1 parent 625fccc commit f45662a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Rector\Tests\Privatization\Rector\ClassMethod\PrivatizeFinalClassMethodRector\Fixture;

final class SkipUnknownParentClass extends SomeUnknownParent
{
protected function someMethod()
{
}
}
34 changes: 34 additions & 0 deletions rules/Privatization/Guard/OverrideByParentClassGuard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Rector\Privatization\Guard;

use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Reflection\ReflectionProvider;

/**
* Verify whether Class_'s method or property allowed to be overridden by verify class parent or implements exists
*/
final class OverrideByParentClassGuard
{
public function __construct(private readonly ReflectionProvider $reflectionProvider)
{
}

public function isLegal(Class_ $class): bool
{
if ($class->extends instanceof FullyQualified && ! $this->reflectionProvider->hasClass($class->extends->toString())) {
return false;
}

foreach ($class->implements as $implement) {
if (! $this->reflectionProvider->hasClass($implement->toString())) {
return false;
}
}

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\Rector\AbstractScopeAwareRector;
use Rector\Privatization\Guard\OverrideByParentClassGuard;
use Rector\Privatization\NodeManipulator\VisibilityManipulator;
use Rector\Privatization\VisibilityGuard\ClassMethodVisibilityGuard;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
Expand All @@ -23,6 +24,7 @@ final class PrivatizeFinalClassMethodRector extends AbstractScopeAwareRector
public function __construct(
private readonly ClassMethodVisibilityGuard $classMethodVisibilityGuard,
private readonly VisibilityManipulator $visibilityManipulator,
private readonly OverrideByParentClassGuard $overrideByParentClassGuard
) {
}

Expand Down Expand Up @@ -71,6 +73,10 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node
return null;
}

if (! $this->overrideByParentClassGuard->isLegal($node)) {
return null;
}

$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return null;
Expand Down

0 comments on commit f45662a

Please sign in to comment.