[CodeQuality] Create UnnecessaryTernaryExpressionRector

This commit is contained in:
Gabriel Caruso 2018-05-13 14:17:15 -03:00
parent 8cc1b69ff3
commit 6950973d48
No known key found for this signature in database
GPG Key ID: D93D6E258EFC438A
7 changed files with 91 additions and 0 deletions

View File

@ -1,2 +1,3 @@
services:
Rector\Rector\Contrib\CodeQuality\InArrayAndArrayKeysToArrayKeyExistsRector: ~
Rector\Rector\Contrib\CodeQuality\UnnecessaryTernaryExpressionRector: ~

View File

@ -179,6 +179,15 @@ Simplify `in_array` and `array_keys` functions combination into `array_key_exist
+array_key_exists("key", $array);
```
## Rector\Rector\Contrib\CodeQuality\UnnecessaryTernaryExpressionRector
Remove unnecessary ternary expressions.
```diff
-$foo === $bar ? true : false;
+$foo === $bar;
```
## Rector\Rector\Dynamic\ParentTypehintedArgumentRector
[Dynamic] Changes defined parent class typehints.

View File

@ -0,0 +1,31 @@
<?php declare(strict_types=1);
namespace Rector\Rector\Contrib\CodeQuality;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class UnnecessaryTernaryExpressionRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition(
'Remove unnecessary ternary expressions.',
[new CodeSample('$foo === $bar ? true : false;', '$foo === $bar;')]
);
}
public function isCandidate(Node $node): bool
{
return true;
}
public function refactor(Node $node): ?Node
{
return $node;
}
}

View File

@ -0,0 +1,9 @@
<?php declare(strict_types=1);
final class MyClass
{
public function unecessaryTernary(): bool
{
return $foo === $bar;
}
}

View File

@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace Rector\Tests\Rector\Contrib\CodeQuality\UnnecessaryTernaryExpressionRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
/**
* @covers \Rector\Rector\Contrib\CodeQuality\UnnecessaryTernaryExpressionRector
*/
final class UnnecessaryTernaryExpressionRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideWrongToFixedFiles()
*/
public function test(string $wrong, string $fixed): void
{
$this->doTestFileMatchesExpectedContent($wrong, $fixed);
}
public function provideWrongToFixedFiles(): Iterator
{
yield [__DIR__ . '/Wrong/wrong.php.inc', __DIR__ . '/Correct/correct.php.inc'];
}
protected function provideConfig(): string
{
return __DIR__ . '/config.yml';
}
}

View File

@ -0,0 +1,9 @@
<?php declare(strict_types=1);
final class MyClass
{
public function unecessaryTernary(): bool
{
return $foo === $bar ? true : false;
}
}

View File

@ -0,0 +1,2 @@
services:
Rector\Rector\Contrib\CodeQuality\UnnecessaryTernaryExpressionRector: ~