diff --git a/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php b/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php index b41d0b18bd5..4003d586319 100644 --- a/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php +++ b/rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php @@ -14,12 +14,14 @@ use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Expr\StaticPropertyFetch; use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\If_; use PhpParser\NodeTraverser; use PHPStan\Reflection\ClassReflection; use PHPStan\Type\MixedType; +use PHPStan\Type\ObjectType; use Rector\NodeManipulator\IfManipulator; use Rector\Rector\AbstractRector; use Rector\Reflection\ReflectionResolver; @@ -156,14 +158,17 @@ private function isInstanceofTheSameType(Instanceof_ $instanceof): ?bool return null; } - $classType = $this->nodeTypeResolver->getType($instanceof->class); - $exprType = $this->nodeTypeResolver->getNativeType($instanceof->expr); + if (! $instanceof->class instanceof FullyQualified) { + return null; + } - if ($classType->equals($exprType)) { - return true; + $exprType = $this->nodeTypeResolver->getNativeType($instanceof->expr); + if (! $exprType instanceof ObjectType) { + return null; } - return $classType->isSuperTypeOf($exprType) + $className = $instanceof->class->toString(); + return $exprType->isInstanceOf($className) ->yes(); } diff --git a/tests/Issues/Issue6480/Fixture/fixture.php.inc b/tests/Issues/Issue6480/Fixture/fixture.php.inc index 1720dc7905d..2cdf0985bdf 100644 --- a/tests/Issues/Issue6480/Fixture/fixture.php.inc +++ b/tests/Issues/Issue6480/Fixture/fixture.php.inc @@ -2,10 +2,12 @@ namespace Rector\Tests\Issues\Issue6480\Fixture; +use Rector\Tests\Issues\Issue6480\Source\ExistingClass; + class Fixture { - function test(Foo $foo, mixed $bar): void { - if ($foo instanceof Foo) { + function test(ExistingClass $foo, mixed $bar): void { + if ($foo instanceof ExistingClass) { var_dump(!empty($bar) ? $bar : null); } } @@ -17,9 +19,11 @@ class Fixture namespace Rector\Tests\Issues\Issue6480\Fixture; +use Rector\Tests\Issues\Issue6480\Source\ExistingClass; + class Fixture { - function test(Foo $foo, mixed $bar): void { + function test(ExistingClass $foo, mixed $bar): void { var_dump(empty($bar) ? null : $bar); } } diff --git a/tests/Issues/Issue6480/Source/ExistingClass.php b/tests/Issues/Issue6480/Source/ExistingClass.php new file mode 100644 index 00000000000..1b1cea4afcd --- /dev/null +++ b/tests/Issues/Issue6480/Source/ExistingClass.php @@ -0,0 +1,10 @@ +