Skip to content

Commit

Permalink
[EarlyReturn] Handle multiple statements in else in ChangeIfElseValue…
Browse files Browse the repository at this point in the history
…AssignToEarlyReturnRector (#4580)

Co-authored-by: Jiří Bok <jiri.bok@nice.com>
  • Loading branch information
dorrogeray and Jiří Bok committed Jul 22, 2023
1 parent c94645b commit a7cd7ed
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Rector\BetterPhpDocParser\PhpDocParser;

use PhpParser\Node as PhpNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\Node;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Rector\Tests\EarlyReturn\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector\Fixture;

class ElseWithMultipleStatementsFixture
{
public function generateNumber(int $bonus, int $multiplier): int
{
if (mt_rand(0, 1) === 1) {
$number = 10;
} else {
$bonus *= $multiplier;
$number = 20 + $bonus;
}

return $number;
}
}

?>
-----
<?php

namespace Rector\Tests\EarlyReturn\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector\Fixture;

class ElseWithMultipleStatementsFixture
{
public function generateNumber(int $bonus, int $multiplier): int
{
if (mt_rand(0, 1) === 1) {
return 10;
}
$bonus *= $multiplier;

return 20 + $bonus;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ public function refactor(Node $node): ?StmtsAwareInterface
$if->else = null;
$stmt->expr = $assign->expr;

$lastStmt = array_pop($node->stmts);
$elseStmtsExceptLast = array_slice($elseStmts, 0, -1);
$node->stmts = [...$node->stmts, ...$elseStmtsExceptLast, $lastStmt];

return $node;
}

Expand Down

0 comments on commit a7cd7ed

Please sign in to comment.