|
5 | 5 | namespace Rector\DeadCode\Rector\Switch_; |
6 | 6 |
|
7 | 7 | use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\Throw_; |
8 | 9 | use PhpParser\Node\Stmt; |
9 | 10 | use PhpParser\Node\Stmt\Break_; |
10 | 11 | use PhpParser\Node\Stmt\Case_; |
| 12 | +use PhpParser\Node\Stmt\Continue_; |
| 13 | +use PhpParser\Node\Stmt\Expression; |
11 | 14 | use PhpParser\Node\Stmt\Return_; |
12 | 15 | use PhpParser\Node\Stmt\Switch_; |
13 | 16 | use Rector\PhpParser\Printer\BetterStandardPrinter; |
@@ -109,6 +112,8 @@ private function removeDuplicatedCases(Switch_ $switch): void |
109 | 112 | /** @var int[] $processedCasesKeys */ |
110 | 113 | $processedCasesKeys = []; |
111 | 114 |
|
| 115 | + $fallThroughCasesKeys = $this->resolveFallThroughCasesKeys($switch); |
| 116 | + |
112 | 117 | foreach ($switch->cases as $outerCaseKey => $outerCase) { |
113 | 118 | if (in_array($outerCaseKey, $processedCasesKeys)) { |
114 | 119 | continue; |
@@ -137,6 +142,12 @@ private function removeDuplicatedCases(Switch_ $switch): void |
137 | 142 | continue; |
138 | 143 | } |
139 | 144 |
|
| 145 | + // moving a case reached by fall-through would change what the previous case runs into |
| 146 | + if (in_array($innerCaseKey, $fallThroughCasesKeys, true)) { |
| 147 | + $casesWithoutStmts = []; |
| 148 | + continue; |
| 149 | + } |
| 150 | + |
140 | 151 | if ($this->areSwitchStmtsEqualsAndWithBreak($outerCase, $innerCase)) { |
141 | 152 | foreach ($casesWithoutStmts as $caseWithoutStmtsKey => $caseWithoutStmts) { |
142 | 153 | $equalCases[] = $caseWithoutStmts; |
@@ -167,6 +178,38 @@ private function removeDuplicatedCases(Switch_ $switch): void |
167 | 178 | $switch->cases = $result; |
168 | 179 | } |
169 | 180 |
|
| 181 | + /** |
| 182 | + * @return int[] |
| 183 | + */ |
| 184 | + private function resolveFallThroughCasesKeys(Switch_ $switch): array |
| 185 | + { |
| 186 | + $fallThroughCasesKeys = []; |
| 187 | + $isPreviousFallingThrough = false; |
| 188 | + |
| 189 | + foreach ($switch->cases as $key => $case) { |
| 190 | + if ($case->stmts === []) { |
| 191 | + continue; |
| 192 | + } |
| 193 | + |
| 194 | + if ($isPreviousFallingThrough) { |
| 195 | + $fallThroughCasesKeys[] = $key; |
| 196 | + } |
| 197 | + |
| 198 | + $isPreviousFallingThrough = ! $this->isTerminatingStmt($case->stmts[array_key_last($case->stmts)]); |
| 199 | + } |
| 200 | + |
| 201 | + return $fallThroughCasesKeys; |
| 202 | + } |
| 203 | + |
| 204 | + private function isTerminatingStmt(Stmt $stmt): bool |
| 205 | + { |
| 206 | + if ($stmt instanceof Break_ || $stmt instanceof Return_ || $stmt instanceof Continue_) { |
| 207 | + return true; |
| 208 | + } |
| 209 | + |
| 210 | + return $stmt instanceof Expression && $stmt->expr instanceof Throw_; |
| 211 | + } |
| 212 | + |
170 | 213 | private function areSwitchStmtsEqualsAndWithBreak(Case_ $currentCase, Case_ $nextCase): bool |
171 | 214 | { |
172 | 215 | /** |
|
0 commit comments