Skip to content

Commit

Permalink
[DeadCode] Skip $this instanceof in Trait on RemoveAlwaysTrueIfCondit…
Browse files Browse the repository at this point in the history
…ionRector (#5817)

* [DeadCode] Skip $this instanceof in Trait on RemoveAlwaysTrueIfConditionRector

* rename trait name
  • Loading branch information
samsonasik committed Apr 12, 2024
1 parent 879a36b commit 7d69fc2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
@@ -0,0 +1,17 @@
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector\Fixture;

use DateTimeInterface;

trait SkipTraitThis
{
public function getIssue(): void
{
foreach (['value_1', 'value_2'] as $value) {
if ($this instanceof DateTimeInterface && $this->getExample() === false) {
$this->setExample('demo');
}
}
}
}
27 changes: 24 additions & 3 deletions rules/DeadCode/NodeAnalyzer/SafeLeftTypeBooleanAndOrAnalyzer.php
Expand Up @@ -4,21 +4,27 @@

namespace Rector\DeadCode\NodeAnalyzer;

use PHPStan\Type\ObjectType;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Variable;
use PHPStan\Reflection\ClassReflection;
use Rector\NodeAnalyzer\ExprAnalyzer;
use Rector\NodeTypeResolver\NodeTypeResolver;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Reflection\ReflectionResolver;

final readonly class SafeLeftTypeBooleanAndOrAnalyzer
{
public function __construct(
private readonly BetterNodeFinder $betterNodeFinder,
private readonly ExprAnalyzer $exprAnalyzer
private readonly ExprAnalyzer $exprAnalyzer,
private readonly ReflectionResolver $reflectionResolver,
private readonly NodeTypeResolver $nodeTypeResolver
) {
}

Expand All @@ -33,10 +39,25 @@ public function isSafe(BooleanAnd|BooleanOr $booleanAnd): bool
return false;
}

// get type from Property and ArrayDimFetch is unreliable
return ! (bool) $this->betterNodeFinder->findFirst(
$hasPropertyFetchOrArrayDimFetch = (bool) $this->betterNodeFinder->findFirst(
$booleanAnd->left,
static fn (Node $node): bool => $node instanceof PropertyFetch || $node instanceof StaticPropertyFetch || $node instanceof ArrayDimFetch
);

// get type from Property and ArrayDimFetch is unreliable
if ($hasPropertyFetchOrArrayDimFetch) {
return false;
}

// skip trait this
$classReflection = $this->reflectionResolver->resolveClassReflection($booleanAnd);
if ($classReflection instanceof ClassReflection && $classReflection->isTrait()) {
return ! (bool) $this->betterNodeFinder->findFirst(
$booleanAnd->left,
fn (Node $node): bool => $this->nodeTypeResolver->getType($node) instanceof ObjectType
);
}

return true;
}
}

0 comments on commit 7d69fc2

Please sign in to comment.