From 98a2a6fd6c6d1e2db5c0143e3e66e8421904b428 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Thu, 21 Mar 2024 12:21:09 +0100 Subject: [PATCH] Add test fixture on boolean && in RemoveAlwaysTrueIfConditionRector (#5749) * add fixture on boolean and * Add boolean and if support to RemoveAlwaysTrueIfConditionRector * [ci-review] Rector Rectify --------- Co-authored-by: GitHub Action --- .../Fixture/boolean_and.php.inc | 35 +++++++++++++++++++ .../If_/RemoveAlwaysTrueIfConditionRector.php | 29 +++++++++++++-- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 rules-tests/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector/Fixture/boolean_and.php.inc diff --git a/rules-tests/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector/Fixture/boolean_and.php.inc b/rules-tests/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector/Fixture/boolean_and.php.inc new file mode 100644 index 00000000000..fe0dec6a1f6 --- /dev/null +++ b/rules-tests/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector/Fixture/boolean_and.php.inc @@ -0,0 +1,35 @@ + +----- + diff --git a/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php b/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php index ef6d8dd6628..f8d290e38b0 100644 --- a/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php +++ b/rules/DeadCode/Rector/If_/RemoveAlwaysTrueIfConditionRector.php @@ -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; @@ -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; } @@ -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; + } }