Skip to content

Commit

Permalink
Use class name directly in RemoveDeadInstanceOfRector (#6087)
Browse files Browse the repository at this point in the history
* Use class name directly in RemoveDeadInstanceOfRector

* use existing class
  • Loading branch information
TomasVotruba authored Jun 30, 2024
1 parent de0dda8 commit 0482641
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
15 changes: 10 additions & 5 deletions rules/DeadCode/Rector/If_/RemoveDeadInstanceOfRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}

Expand Down
10 changes: 7 additions & 3 deletions tests/Issues/Issue6480/Fixture/fixture.php.inc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand All @@ -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);
}
}
Expand Down
10 changes: 10 additions & 0 deletions tests/Issues/Issue6480/Source/ExistingClass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Issues\Issue6480\Source;

final class ExistingClass
{

}

0 comments on commit 0482641

Please sign in to comment.