add TernaryToElvisRector

This commit is contained in:
Tomas Votruba 2018-12-15 16:31:40 +01:00
parent daa8f01688
commit 7ed7368dac
5 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,2 @@
services:
Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector: ~

View File

@ -0,0 +1,59 @@
<?php declare(strict_types=1);
namespace Rector\CodeQuality\Rector\Ternary;
use PhpParser\Node;
use PhpParser\Node\Expr\Ternary;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
/**
* @see http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
* @see https://stackoverflow.com/a/1993455/1348344
*/
final class TernaryToElvisRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Use ?: instead of ?, where useful', [
new CodeSample(
<<<'CODE_SAMPLE'
function elvis()
{
$value = $a ? $a : false;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
function elvis()
{
$value = $a ?: false;
}
CODE_SAMPLE
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [Ternary::class];
}
/**
* @param Ternary $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->areNodesEqual($node->cond, $node->if)) {
return null;
}
$node->if = null;
return $node;
}
}

View File

@ -0,0 +1,17 @@
<?php
function elvis()
{
$value = $a ? $a : false;
}
?>
-----
<?php
function elvis()
{
$value = $a ?: false;
}
?>

View File

@ -0,0 +1,19 @@
<?php declare(strict_types=1);
namespace Rector\CodeQuality\Tests\Rector\Ternary\TernaryToElvisRector;
use Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
final class TernaryToElvisRectorTest extends AbstractRectorTestCase
{
public function test(): void
{
$this->doTestFiles([__DIR__ . '/Fixture/fixture.php.inc']);
}
protected function getRectorClass(): string
{
return TernaryToElvisRector::class;
}
}

View File

@ -0,0 +1,2 @@
services:
Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector: ~