rector/packages/CodeQuality/src/Rector/If_/ShortenElseIfRector.php

104 lines
2.0 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\If_;
use PhpParser\Node;
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\If_;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
/**
* @see \Rector\CodeQuality\Tests\Rector\If_\ShortenElseIfRector\ShortenElseIfRectorTest
*/
final class ShortenElseIfRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Shortens else/if to elseif', [
new CodeSample(
<<<'PHP'
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
} else {
if ($cond2) {
return $action2;
}
}
}
}
PHP
,
<<<'PHP'
class SomeClass
{
public function run()
{
if ($cond1) {
return $action1;
} elseif ($cond2) {
return $action2;
}
}
}
PHP
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [If_::class];
}
/**
* @param If_ $node
*/
public function refactor(Node $node): ?Node
{
2019-10-04 13:08:10 +00:00
return $this->shortenElseIf($node);
}
private function shortenElseIf(If_ $node): ?Node
{
2019-10-04 17:31:24 +00:00
if ($node->else === null) {
return null;
}
2019-10-04 17:31:24 +00:00
$else = $node->else;
if (count($else->stmts) > 1) {
return null;
}
$if = $else->stmts[0];
if (! $if instanceof If_) {
return null;
}
2019-10-04 13:08:10 +00:00
// Try to shorten the nested if before transforming it to elseif
$refactored = $this->shortenElseIf($if);
2019-10-30 14:38:30 +00:00
if ($refactored !== null) {
$if = $refactored;
}
2019-10-04 17:31:24 +00:00
$node->elseifs[] = new ElseIf_($if->cond, $if->stmts);
$node->else = $if->else;
$node->elseifs = array_merge($node->elseifs, $if->elseifs);
return $node;
}
}