Skip to content

Commit

Permalink
[CodeQuality] Skip with break on SwitchTrueToIfRector (#3634)
Browse files Browse the repository at this point in the history
* Add failing test fixture for SwitchTrueToIfRector

# Failing Test for SwitchTrueToIfRector

Based on https://getrector.com/demo/4ea2ecee-99f7-474e-b74e-a2db47a1e1eb

* fix

* Final touch: use end($case->stmts) to be Return_ stmt check

---------

Co-authored-by: pgr-dS <110042614+pgr-dS@users.noreply.github.com>
  • Loading branch information
samsonasik and pgr-dS committed Apr 20, 2023
1 parent f453969 commit f08216f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Switch_\SwitchTrueToIfRector\Fixture;

final class SkipBreak
{
public function run(int $int): string
{
$str = 'error';
switch (true) {
case $int === 0:
$str = 'zero';
break;
case $int%2 === 1:
$str = 'odd';
break;
case $int%2 === 0:
$str = 'even';
break;
}

return $str;
}
}
?>
5 changes: 5 additions & 0 deletions rules/CodeQuality/Rector/Switch_/SwitchTrueToIfRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
Expand Down Expand Up @@ -87,6 +88,10 @@ public function refactor(Node $node): ?array
$defaultCase = null;

foreach ($node->cases as $case) {
if (! end($case->stmts) instanceof Return_) {
return null;
}

if (! $case->cond instanceof Expr) {
$defaultCase = $case;
continue;
Expand Down

0 comments on commit f08216f

Please sign in to comment.