From dd8086fb53be6401f9653bec1d4025a4eeba70f1 Mon Sep 17 00:00:00 2001 From: Peter Fox Date: Sat, 11 Jan 2025 15:35:13 +0000 Subject: [PATCH] Fix for Match to Switch when inside binary operation (#263) * working test * Working fix * rector fix * fixes --- .../DowngradeMatchToSwitchRector.php | 23 +++++++- tests/Set/Fixture/match_in_binary_op.php.inc | 53 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 tests/Set/Fixture/match_in_binary_op.php.inc diff --git a/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php b/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php index 205f138a..5f7ba9bb 100644 --- a/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php +++ b/rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php @@ -7,8 +7,10 @@ use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\ArrayItem; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\ArrowFunction; use PhpParser\Node\Expr\Assign; +use PhpParser\Node\Expr\BinaryOp; use PhpParser\Node\Expr\CallLike; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\Match_; @@ -294,7 +296,11 @@ private function createSwitchStmts( } elseif ($matchArm->body instanceof Throw_) { $stmts[] = new Expression($matchArm->body); } elseif ($node instanceof Return_) { - $stmts[] = new Return_($matchArm->body); + if ($node->expr instanceof BinaryOp) { + $stmts[] = $this->replicateBinaryOp($node->expr, $matchArm->body); + } else { + $stmts[] = new Return_($matchArm->body); + } } elseif ($node instanceof Echo_) { $stmts[] = new Echo_([$matchArm->body]); $stmts[] = new Break_(); @@ -314,4 +320,19 @@ private function createSwitchStmts( return $stmts; } + + private function replicateBinaryOp(BinaryOp $binaryOp, Expr $expr): Return_ + { + $newExpr = clone $binaryOp; + // remove the match statement from the binary operation + $this->traverseNodesWithCallable($newExpr, static function (Node $node) use ($expr): ?Expr { + if ($node instanceof Match_) { + return $expr; + } + + return null; + }); + + return new Return_($newExpr); + } } diff --git a/tests/Set/Fixture/match_in_binary_op.php.inc b/tests/Set/Fixture/match_in_binary_op.php.inc new file mode 100644 index 00000000..de44e5ff --- /dev/null +++ b/tests/Set/Fixture/match_in_binary_op.php.inc @@ -0,0 +1,53 @@ + true, + default => false, + } && $booleanFlag; + } + + public function runTwo($value, $booleanFlag) + { + return match (true) { + $value === 2 => true, + default => false, + } || $booleanFlag; + } +} + +?> +----- +