fix duplicate switch without break

This commit is contained in:
TomasVotruba 2020-02-21 13:36:24 +01:00
parent fd54cf2eaf
commit 1e83e78a5e
2 changed files with 44 additions and 1 deletions

View File

@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Rector\DeadCode\Rector\Switch_;
use PhpParser\Node;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
@ -80,7 +82,7 @@ PHP
/** @var Case_|null $previousCase */
$previousCase = null;
foreach ($node->cases as $case) {
if ($previousCase && $this->areNodesEqual($case->stmts, $previousCase->stmts)) {
if ($previousCase && $this->areSwitchStmtsEqualsAndWithBreak($case, $previousCase)) {
$previousCase->stmts = [];
}
@ -89,4 +91,23 @@ PHP
return $node;
}
private function areSwitchStmtsEqualsAndWithBreak(Case_ $currentCase, Case_ $previousCase): bool
{
if (! $this->areNodesEqual($currentCase->stmts, $previousCase->stmts)) {
return false;
}
foreach ($currentCase->stmts as $stmt) {
if ($stmt instanceof Break_) {
return true;
}
if ($stmt instanceof Return_) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace Rector\DeadCode\Tests\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector\Fixture;
class SkipNoBreak
{
public function run($max)
{
$letter = 't';
switch ($letter) {
case 't':
$max *= 1024;
// no break
case 'g':
$max *= 1024;
// no break
}
return $max;
}
}