Skip to content

Commit dd8086f

Browse files
authored
Fix for Match to Switch when inside binary operation (#263)
* working test * Working fix * rector fix * fixes
1 parent f9cc5a0 commit dd8086f

File tree

2 files changed

+75
-1
lines changed

2 files changed

+75
-1
lines changed

rules/DowngradePhp80/Rector/Expression/DowngradeMatchToSwitchRector.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
use PhpParser\Node;
88
use PhpParser\Node\Arg;
99
use PhpParser\Node\ArrayItem;
10+
use PhpParser\Node\Expr;
1011
use PhpParser\Node\Expr\ArrowFunction;
1112
use PhpParser\Node\Expr\Assign;
13+
use PhpParser\Node\Expr\BinaryOp;
1214
use PhpParser\Node\Expr\CallLike;
1315
use PhpParser\Node\Expr\FuncCall;
1416
use PhpParser\Node\Expr\Match_;
@@ -294,7 +296,11 @@ private function createSwitchStmts(
294296
} elseif ($matchArm->body instanceof Throw_) {
295297
$stmts[] = new Expression($matchArm->body);
296298
} elseif ($node instanceof Return_) {
297-
$stmts[] = new Return_($matchArm->body);
299+
if ($node->expr instanceof BinaryOp) {
300+
$stmts[] = $this->replicateBinaryOp($node->expr, $matchArm->body);
301+
} else {
302+
$stmts[] = new Return_($matchArm->body);
303+
}
298304
} elseif ($node instanceof Echo_) {
299305
$stmts[] = new Echo_([$matchArm->body]);
300306
$stmts[] = new Break_();
@@ -314,4 +320,19 @@ private function createSwitchStmts(
314320

315321
return $stmts;
316322
}
323+
324+
private function replicateBinaryOp(BinaryOp $binaryOp, Expr $expr): Return_
325+
{
326+
$newExpr = clone $binaryOp;
327+
// remove the match statement from the binary operation
328+
$this->traverseNodesWithCallable($newExpr, static function (Node $node) use ($expr): ?Expr {
329+
if ($node instanceof Match_) {
330+
return $expr;
331+
}
332+
333+
return null;
334+
});
335+
336+
return new Return_($newExpr);
337+
}
317338
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
namespace Rector\Tests\Set\Fixture;
4+
5+
final class MatchInBinaryOp
6+
{
7+
public function run($value, $booleanFlag)
8+
{
9+
return match (true) {
10+
$value === 2 => true,
11+
default => false,
12+
} && $booleanFlag;
13+
}
14+
15+
public function runTwo($value, $booleanFlag)
16+
{
17+
return match (true) {
18+
$value === 2 => true,
19+
default => false,
20+
} || $booleanFlag;
21+
}
22+
}
23+
24+
?>
25+
-----
26+
<?php
27+
28+
namespace Rector\Tests\Set\Fixture;
29+
30+
final class MatchInBinaryOp
31+
{
32+
public function run($value, $booleanFlag)
33+
{
34+
switch (true) {
35+
case $value === 2:
36+
return true && $booleanFlag;
37+
default:
38+
return false && $booleanFlag;
39+
}
40+
}
41+
42+
public function runTwo($value, $booleanFlag)
43+
{
44+
switch (true) {
45+
case $value === 2:
46+
return true || $booleanFlag;
47+
default:
48+
return false || $booleanFlag;
49+
}
50+
}
51+
}
52+
53+
?>

0 commit comments

Comments
 (0)