Skip to content

Commit

Permalink
[DeadCode][CodeQuality] Handle SimplifyIfElseToTernaryRector + Remove…
Browse files Browse the repository at this point in the history
…UnusedAssignVariableRector (#789)

Co-authored-by: Bl00D4NGEL <kuhlesdominik@gmx.de>
  • Loading branch information
samsonasik and Bl00D4NGEL committed Aug 30, 2021
1 parent a81fd4e commit f257b10
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ public function refactor(Node $node): ?Node
return null;
}

// @see https://github.com/rectorphp/rector/issues/6655
// verify current statement is a Node before removing or use its Assign Expr
$currentStatement = $node->getAttribute(AttributeKey::CURRENT_STATEMENT);
if (! $currentStatement instanceof Node) {
return null;
}

// is scalar assign? remove whole
if (! $this->sideEffectNodeDetector->detect($node->expr)) {
$this->removeNode($node);
Expand Down
23 changes: 23 additions & 0 deletions tests/Issues/Issue6655/Fixture/fixture.php.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

function getRes(): string
{
if ('a' !== 'b') {
$res = "a";
} else {
$res = "b";
}

return $res;
}
?>
-----
<?php

function getRes(): string
{
$res = 'a' !== 'b' ? "a" : "b";

return $res;
}
?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Rector\Core\Tests\Issues\Issue6655;

use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;

/**
* @see https://github.com/rectorphp/rector/issues/6655
*/
final class SimplifyIfElseAndRemoveUnusedAssignVariableTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}

/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
12 changes: 12 additions & 0 deletions tests/Issues/Issue6655/config/configured_rule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use Rector\DeadCode\Rector\Assign\RemoveUnusedAssignVariableRector;
use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();

$services->set(SimplifyIfElseToTernaryRector::class);
$services->set(RemoveUnusedAssignVariableRector::class);
};

0 comments on commit f257b10

Please sign in to comment.