Skip to content

Commit

Permalink
[Php70] Remove previous attribute usage on ReduceMultipleDefaultSwitc…
Browse files Browse the repository at this point in the history
…hRector (#3537)
  • Loading branch information
samsonasik committed Mar 29, 2023
1 parent 180d9a4 commit 0d5169d
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions rules/Php70/Rector/Switch_/ReduceMultipleDefaultSwitchRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use PhpParser\Node\Stmt\Switch_;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
Expand Down Expand Up @@ -72,45 +71,51 @@ public function getNodeTypes(): array
public function refactor(Node $node): ?Node
{
$defaultCases = [];
foreach ($node->cases as $case) {
foreach ($node->cases as $key => $case) {
if ($case->cond instanceof Expr) {
continue;
}

$defaultCases[] = $case;
$defaultCases[$key] = $case;
}

if (count($defaultCases) < 2) {
return null;
}

$this->removeExtraDefaultCases($defaultCases);
$this->removeExtraDefaultCases($node->cases, $defaultCases);

return $node;
}

/**
* @param Case_[] $cases
* @param Case_[] $defaultCases
*/
private function removeExtraDefaultCases(array $defaultCases): void
private function removeExtraDefaultCases(array $cases, array $defaultCases): void
{
// keep only last
array_pop($defaultCases);
foreach ($defaultCases as $defaultCase) {
$this->keepStatementsToParentCase($defaultCase);

foreach ($defaultCases as $key => $defaultCase) {
$this->keepStatementsToParentCase($cases, $defaultCase, $key);
$this->removeNode($defaultCase);
}
}

private function keepStatementsToParentCase(Case_ $case): void
/**
* @param Case_[] $cases
*/
private function keepStatementsToParentCase(array $cases, Case_ $case, int $key): void
{
$previousNode = $case->getAttribute(AttributeKey::PREVIOUS_NODE);
if (! $previousNode instanceof Case_) {
if (! isset($cases[$key - 1])) {
return;
}

if ($previousNode->stmts === []) {
$previousNode->stmts = $case->stmts;
$previousCase = $cases[$key - 1];

if ($previousCase->stmts === []) {
$previousCase->stmts = $case->stmts;
$case->stmts = [];
}
}
Expand Down

0 comments on commit 0d5169d

Please sign in to comment.