|
11 | 11 | use PhpParser\Node\Expr\ConstFetch; |
12 | 12 | use PhpParser\Node\Expr\MethodCall; |
13 | 13 | use PhpParser\Node\Expr\PropertyFetch; |
| 14 | +use PhpParser\Node\Expr\Throw_; |
14 | 15 | use PhpParser\Node\Expr\Variable; |
15 | 16 | use PhpParser\Node\Identifier; |
16 | 17 | use PhpParser\Node\Scalar; |
17 | 18 | use PhpParser\Node\Scalar\String_; |
18 | 19 | use PhpParser\Node\Stmt\Class_; |
| 20 | +use PhpParser\Node\Stmt\Expression; |
19 | 21 | use PhpParser\Node\Stmt\Function_; |
20 | 22 | use PhpParser\Node\Stmt\Return_; |
21 | 23 | use PhpParser\NodeFinder; |
@@ -275,21 +277,39 @@ private function refactorClosureToVoid(Closure $closure): bool |
275 | 277 | return false; |
276 | 278 | } |
277 | 279 |
|
278 | | - // only strip side-effect-free values, to not lose behavior |
| 280 | + // only strip side-effect-free values or a "return throw", to not lose behavior |
279 | 281 | foreach ($valueReturns as $valueReturn) { |
280 | 282 | $returnedExpr = $valueReturn->expr; |
281 | 283 | if (! $returnedExpr instanceof Expr) { |
282 | 284 | continue; |
283 | 285 | } |
284 | 286 |
|
| 287 | + // "return throw new X" becomes a bare "throw new X" statement below |
| 288 | + if ($returnedExpr instanceof Throw_) { |
| 289 | + continue; |
| 290 | + } |
| 291 | + |
285 | 292 | if (! $this->isPureValue($returnedExpr)) { |
286 | 293 | return false; |
287 | 294 | } |
288 | 295 | } |
289 | 296 |
|
290 | | - foreach ($valueReturns as $valueReturn) { |
291 | | - $valueReturn->expr = null; |
292 | | - } |
| 297 | + $this->traverseNodesWithCallable($closure->stmts, static function (Node $subNode): ?Expression { |
| 298 | + if (! $subNode instanceof Return_) { |
| 299 | + return null; |
| 300 | + } |
| 301 | + |
| 302 | + // "return throw new X;" is itself invalid in a void function, unwrap to "throw new X;" |
| 303 | + if ($subNode->expr instanceof Throw_) { |
| 304 | + return new Expression($subNode->expr); |
| 305 | + } |
| 306 | + |
| 307 | + if ($subNode->expr instanceof Expr) { |
| 308 | + $subNode->expr = null; |
| 309 | + } |
| 310 | + |
| 311 | + return null; |
| 312 | + }); |
293 | 313 |
|
294 | 314 | // drop a now-empty trailing "return;" |
295 | 315 | $lastStmt = $closure->stmts[array_key_last($closure->stmts)] ?? null; |
|
0 commit comments