Skip to content

Commit

Permalink
Add test fixture on boolean && in RemoveAlwaysTrueIfConditionRector (#…
Browse files Browse the repository at this point in the history
…5749)

* add fixture on boolean and

* Add boolean and if support to RemoveAlwaysTrueIfConditionRector

* [ci-review] Rector Rectify

---------

Co-authored-by: GitHub Action <actions@github.com>
  • Loading branch information
TomasVotruba and actions-user authored Mar 21, 2024
1 parent da67bb9 commit 98a2a6f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

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

final class BooleanAndWithObject
{
public function run(\stdClass $someObject)
{
if (is_object($someObject) && method_exists($someObject, 'some_method')) {
return 100;
}

return 0;
}
}

?>
-----
<?php

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

final class BooleanAndWithObject
{
public function run(\stdClass $someObject)
{
if (method_exists($someObject, 'some_method')) {
return 100;
}

return 0;
}
}

?>
29 changes: 27 additions & 2 deletions rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Variable;
Expand Down Expand Up @@ -78,10 +79,14 @@ public function getNodeTypes(): array

/**
* @param If_ $node
* @return int|null|Stmt[]
* @return int|null|Stmt[]|If_
*/
public function refactor(Node $node): int|null|array
public function refactor(Node $node): int|null|array|If_
{
if ($node->cond instanceof BooleanAnd) {
return $this->refactorIfWithBooleanAnd($node);
}

if ($node->else instanceof Else_) {
return null;
}
Expand Down Expand Up @@ -164,4 +169,24 @@ private function shouldSkipPropertyFetch(Expr $expr): bool

return false;
}

private function refactorIfWithBooleanAnd(If_ $if): ?If_
{
if (! $if->cond instanceof BooleanAnd) {
return null;
}

$booleanAnd = $if->cond;
$leftType = $this->getType($booleanAnd->left);
if (! $leftType instanceof ConstantBooleanType) {
return null;
}

if (!$leftType->getValue()) {
return null;
}

$if->cond = $booleanAnd->right;
return $if;
}
}

0 comments on commit 98a2a6f

Please sign in to comment.