Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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];
}
}
Original file line number Diff line number Diff line change
@@ -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';
}
}

?>
Original file line number Diff line number Diff line change
@@ -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;
}
}