Merge pull request #2346 from fsok/skip_continue_with_argument

[PHP] ContinueToBreakInSwitchRector skip continue with argument >1
This commit is contained in:
Tomáš Votruba 2019-11-23 20:53:51 +01:00 committed by GitHub
commit 0d19f41479
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 1 deletions

View File

@ -5,9 +5,13 @@ declare(strict_types=1);
namespace Rector\Php52\Rector\Switch_;
use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Continue_;
use PhpParser\Node\Stmt\Switch_;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\ConstantType;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
@ -69,7 +73,37 @@ PHP
foreach ($node->cases as $case) {
foreach ($case->stmts as $key => $caseStmt) {
if ($caseStmt instanceof Continue_) {
$case->stmts[$key] = new Break_();
$case->stmts[$key] = $this->processContinueStatement($caseStmt);
}
}
}
return $node;
}
private function processContinueStatement(Continue_ $node): Node
{
if ($node->num === null) {
return new Break_();
} elseif ($node->num instanceof LNumber) {
if ($this->getValue($node->num) <= 1) {
return new Break_();
}
} elseif ($node->num instanceof Variable) {
return $this->processVariableNum($node, $node->num);
}
return $node;
}
private function processVariableNum(Continue_ $node, Variable $numVariable): Node
{
$staticType = $this->getStaticType($numVariable);
if ($staticType instanceof ConstantType) {
if ($staticType instanceof ConstantIntegerType) {
if ($staticType->getValue() <= 1) {
return new Break_();
}
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Rector\Php52\Tests\Rector\Switch_\ContinueToBreakInSwitchRector\Fixture;
function skip_continue_with_argument(array $array)
{
$x = 2;
foreach ($array as $item) {
switch ($item) {
case 1:
echo "$item\n";
continue 2;
case 2:
echo "$item\n";
continue $x;
default:
echo "default\n";
break;
}
echo "loop\n";
}
}