[DeadCode] Add RemoveAlwaysTrueIfConditionRector (#1924)

[DeadCode] Add RemoveAlwaysTrueIfConditionRector
This commit is contained in:
Tomáš Votruba 2019-08-29 22:41:53 +02:00 committed by GitHub
commit 400689504a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 137 additions and 0 deletions

View File

@ -0,0 +1,85 @@
<?php declare(strict_types=1);
namespace Rector\DeadCode\Rector\If_;
use PhpParser\Node;
use PhpParser\Node\Stmt\If_;
use PHPStan\Type\Constant\ConstantBooleanType;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class RemoveAlwaysTrueIfConditionRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Remove if condition that is always true', [
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
public function go()
{
if (1 === 1) {
return 'yes';
}
return 'no';
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
public function go()
{
return 'yes';
return 'no';
}
}
CODE_SAMPLE
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [If_::class];
}
/**
* @param If_ $node
*/
public function refactor(Node $node): ?Node
{
if ($node->else !== null) {
return null;
}
// just one if
if (count($node->elseifs) !== 0) {
return null;
}
$conditionStaticType = $this->getStaticType($node->cond);
if (! $conditionStaticType instanceof ConstantBooleanType) {
return null;
}
if ($conditionStaticType->getValue() !== true) {
return null;
}
if (count($node->stmts) !== 1) {
// unable to handle now
return null;
}
return $node->stmts[0];
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace Rector\DeadCode\Tests\Rector\If_\RemoveAlwaysTrueIfConditionRector\Fixture;
class RemoveIf
{
public function run()
{
if (true === true) {
return 'hi';
}
return 'hello';
}
}
?>
-----
<?php
namespace Rector\DeadCode\Tests\Rector\If_\RemoveAlwaysTrueIfConditionRector\Fixture;
class RemoveIf
{
public function run()
{
return 'hi';
return 'hello';
}
}
?>

View File

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