Skip to content

Commit

Permalink
[PHP 8.0] Include instant returns in match (rectorphp#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba authored Jun 8, 2021
1 parent e3e31f5 commit ca1cdfa
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

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

final class DoubleReturnWithDefault
{
public static function toStorageValue($input): string
{
switch ($input) {
case 100:
return 'yes';
case 200:
return 'no';
default:
throw new \RuntimeException;
}
}
}

?>
-----
<?php

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

final class DoubleReturnWithDefault
{
public static function toStorageValue($input): string
{
return match ($input) {
100 => 'yes',
200 => 'no',
default => throw new \RuntimeException,
};
}
}

?>
23 changes: 19 additions & 4 deletions rules/Php80/NodeAnalyzer/SwitchAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use PhpParser\Node;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;

final class SwitchAnalyzer
Expand All @@ -22,10 +24,8 @@ public function hasEachCaseBreak(Switch_ $switch): bool
return true;
}

foreach ($case->stmts as $caseStmt) {
if ($caseStmt instanceof Break_) {
continue 2;
}
if ($this->hasBreakOrReturn($case)) {
continue;
}

return false;
Expand Down Expand Up @@ -57,4 +57,19 @@ public function hasDefault(Switch_ $switch): bool

return false;
}

private function hasBreakOrReturn(Case_ $case): bool
{
foreach ($case->stmts as $caseStmt) {
if ($caseStmt instanceof Break_) {
return true;
}

if ($caseStmt instanceof Return_) {
return true;
}
}

return false;
}
}
6 changes: 6 additions & 0 deletions rules/Php80/NodeResolver/SwitchExprsResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function resolve(Switch_ $switch): array
if (! $returnedExpr instanceof Expr) {
return [];
}

$condAndExpr[] = new CondAndExpr($case->cond, $returnedExpr, CondAndExpr::TYPE_RETURN);
} elseif ($expr instanceof Assign) {
$condAndExpr[] = new CondAndExpr($case->cond, $expr, CondAndExpr::TYPE_ASSIGN);
Expand Down Expand Up @@ -71,6 +72,11 @@ private function isValidCase(Case_ $case): bool
return true;
}

// instant return
if ($case->stmts[0] instanceof Return_) {
return true;
}

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

0 comments on commit ca1cdfa

Please sign in to comment.