mirror of
https://github.com/rectorphp/rector.git
synced 2024-07-30 21:30:23 +00:00
add TernaryToElvisRector
This commit is contained in:
parent
daa8f01688
commit
7ed7368dac
2
config/level/php/php53.yml
Normal file
2
config/level/php/php53.yml
Normal file
@ -0,0 +1,2 @@
|
||||
services:
|
||||
Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector: ~
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
function elvis()
|
||||
{
|
||||
$value = $a ? $a : false;
|
||||
}
|
||||
|
||||
?>
|
||||
-----
|
||||
<?php
|
||||
|
||||
function elvis()
|
||||
{
|
||||
$value = $a ?: false;
|
||||
}
|
||||
|
||||
?>
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
services:
|
||||
Rector\CodeQuality\Rector\Ternary\TernaryToElvisRector: ~
|
Loading…
Reference in New Issue
Block a user