Skip to content

Commit

Permalink
[PHP 8.0] Improve single case check (#175)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jun 8, 2021
1 parent 7de2aa4 commit 6e320ce
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

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

final class SkipMultiStmts
{
public function run($value)
{
switch ($value) {
case 1:
$one = 500;
$two = 500;
break;

default:
$one = 1000;
$two = 1000;
break;
}
}
}
25 changes: 24 additions & 1 deletion rules/Php80/NodeResolver/SwitchExprsResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
Expand All @@ -22,7 +24,8 @@ public function resolve(Switch_ $switch): array
$condAndExpr = [];

foreach ($switch->cases as $case) {
if (! isset($case->stmts[0])) {
// must be exactly 1 stmt and break
if (! $this->isValidCase($case)) {
return [];
}

Expand Down Expand Up @@ -51,4 +54,24 @@ public function resolve(Switch_ $switch): array

return $condAndExpr;
}

private function isValidCase(Case_ $case): bool
{
if (count($case->stmts) === 2 && $case->stmts[1] instanceof Break_) {
return true;
}

// default throws stmts
if (count($case->stmts) !== 1) {
return false;
}

// throws expressoin
if ($case->stmts[0] instanceof Throw_) {
return true;
}

// default value
return $case->cond === null;
}
}

0 comments on commit 6e320ce

Please sign in to comment.