Skip to content

Commit

Permalink
[Php80] Handle default in previous not used in next switch (#2335)
Browse files Browse the repository at this point in the history
* [Php80] Handle default in previous not used in next switch

* debug

* Fixed 🎉

* Fixed 🎉
  • Loading branch information
samsonasik committed May 19, 2022
1 parent 3f0a0b7 commit 1a56ec1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Rector\Tests\Php80\Rector\Switch_\ChangeSwitchToMatchRector\Fixture;

final class DefaultInPreviousNotUsedNextSwitch
{
public function run($input)
{
$result = '';
switch ($input) {
case 'a':
case 'b':
$result = 0;
break;
case 'Monsieur':
$result = 1;
break;
}
}
}

?>
-----
<?php

namespace Rector\Tests\Php80\Rector\Switch_\ChangeSwitchToMatchRector\Fixture;

final class DefaultInPreviousNotUsedNextSwitch
{
public function run($input)
{
$result = match ($input) {
'a', 'b' => 0,
'Monsieur' => 1,
default => '',
};
}
}

?>
3 changes: 3 additions & 0 deletions rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Expr\Throw_;
use PhpParser\Node\MatchArm;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
Expand Down Expand Up @@ -161,6 +162,8 @@ private function changeToAssign(Switch_ $switch, Match_ $match, Expr $assignExpr
if ($this->nodeComparator->areNodesEqual($default, $prevInitializedAssign->var)) {
return $assign;
}
} else {
$match->arms[count($match->arms)] = new MatchArm(null, $prevInitializedAssign->expr);
}

$parentAssign = $prevInitializedAssign->getAttribute(AttributeKey::PARENT_NODE);
Expand Down

0 comments on commit 1a56ec1

Please sign in to comment.