From ca1cdfa8705d38acd10c26d79db630f7d2b96874 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Tue, 8 Jun 2021 10:11:25 +0200 Subject: [PATCH] [PHP 8.0] Include instant returns in match (#177) --- .../double_return_with_default.php.inc | 38 +++++++++++++++++++ rules/Php80/NodeAnalyzer/SwitchAnalyzer.php | 23 +++++++++-- .../NodeResolver/SwitchExprsResolver.php | 6 +++ 3 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 rules-tests/Php80/Rector/Switch_/ChangeSwitchToMatchRector/Fixture/double_return_with_default.php.inc diff --git a/rules-tests/Php80/Rector/Switch_/ChangeSwitchToMatchRector/Fixture/double_return_with_default.php.inc b/rules-tests/Php80/Rector/Switch_/ChangeSwitchToMatchRector/Fixture/double_return_with_default.php.inc new file mode 100644 index 000000000000..f7eb1882e532 --- /dev/null +++ b/rules-tests/Php80/Rector/Switch_/ChangeSwitchToMatchRector/Fixture/double_return_with_default.php.inc @@ -0,0 +1,38 @@ + +----- + 'yes', + 200 => 'no', + default => throw new \RuntimeException, + }; + } +} + +?> diff --git a/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php b/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php index d2e37bc2accf..2f2c459a0f5f 100644 --- a/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php +++ b/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php @@ -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 @@ -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; @@ -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; + } } diff --git a/rules/Php80/NodeResolver/SwitchExprsResolver.php b/rules/Php80/NodeResolver/SwitchExprsResolver.php index 0ae0e73ecd0a..48bdef1c9cf6 100644 --- a/rules/Php80/NodeResolver/SwitchExprsResolver.php +++ b/rules/Php80/NodeResolver/SwitchExprsResolver.php @@ -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); @@ -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; }