[DeadCode] Add RemoveDuplicatedArrayKeyRector

This commit is contained in:
Tomas Votruba 2018-12-25 14:11:31 +01:00
parent 157685642d
commit b09976b828
5 changed files with 131 additions and 1 deletions

View File

@ -0,0 +1,3 @@
services:
Rector\DeadCode\Rector\Stmt\RemoveDeadStmtRector: ~
Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector: ~

View File

@ -6,7 +6,6 @@ use PhpParser\Node;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
_Source_
final class _Name_ extends AbstractRector
{

View File

@ -0,0 +1,64 @@
<?php declare(strict_types=1);
namespace Rector\DeadCode\Rector\Array_;
use PhpParser\Node;
use PhpParser\Node\Expr\Array_;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class RemoveDuplicatedArrayKeyRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Remove duplicated key in defined arrays.', [
new CodeSample(
<<<'CODE_SAMPLE'
$item = [
1 => 'A',
1 => 'A'
];
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$item = [
1 => 'A',
];
CODE_SAMPLE
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [Array_::class];
}
/**
* @param Array_ $node
*/
public function refactor(Node $node): ?Node
{
$arrayKeyValues = [];
foreach ($node->items as $arrayItem) {
if ($arrayItem->key === null) {
continue;
}
$keyAndValue = $this->print($arrayItem->key) . $this->print($arrayItem->value);
// already set the same value
if (in_array($keyAndValue, $arrayKeyValues, true)) {
$this->removeNode($arrayItem);
} else {
$arrayKeyValues[] = $keyAndValue;
}
}
return $node;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace Rector\DeadCode\Tests\Rector\Array_\RemoveDuplicatedArrayKeyRector\Fixture;
class Items
{
public function lists()
{
$items = [
1 => 'A',
1 => 'B',
1 => 'A'
];
$key = 1;
$items = [
$key => 'A',
$key => 'A',
];
}
}
?>
-----
<?php
namespace Rector\DeadCode\Tests\Rector\Array_\RemoveDuplicatedArrayKeyRector\Fixture;
class Items
{
public function lists()
{
$items = [
1 => 'A',
1 => 'B'
];
$key = 1;
$items = [
$key => 'A',
];
}
}
?>

View File

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