Skip to content

Commit

Permalink
[DeadCode] Skip RemoveDuplicatedArrayKeyRector on ++index or --index (#…
Browse files Browse the repository at this point in the history
…3606)

* [DeadCode] Skip RemoveDuplicatedArrayKeyRector on ++index or --index

* [DeadCode] Skip RemoveDuplicatedArrayKeyRector on ++index or --index

* rename

* eol

* phpstan
  • Loading branch information
samsonasik committed Apr 11, 2023
1 parent 951e9f9 commit 5ea7727
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector\Fixture;

final class SkipDuplicatePreIncDecrement
{
public function run()
{
$index = 0;

[
$index => 'Max',
++$index => 'Max Ϙ',
++$index => 'Last',
];

[
$index => 'Max',
--$index => 'Max Ϙ',
--$index => 'Last',
];
}
}
34 changes: 27 additions & 7 deletions rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\PreDec;
use PhpParser\Node\Expr\PreInc;
use Rector\Core\Contract\PhpParser\NodePrinterInterface;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\MultiInstanceofChecker;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

Expand All @@ -19,8 +22,14 @@
*/
final class RemoveDuplicatedArrayKeyRector extends AbstractRector
{
/**
* @var array<class-string<Expr>>
*/
private const ALLOWED_KEY_DUPLICATES = [PreInc::class, PreDec::class];

public function __construct(
private readonly NodePrinterInterface $nodePrinter
private readonly NodePrinterInterface $nodePrinter,
private readonly MultiInstanceofChecker $multiInstanceofChecker
) {
}

Expand Down Expand Up @@ -100,12 +109,23 @@ private function getArrayItemsWithDuplicatedKey(Array_ $array): array
*/
private function filterItemsWithSameKey(array $arrayItemsByKeys): array
{
/** @var ArrayItem[][] $arrayItemsByKeys */
$arrayItemsByKeys = array_filter(
$arrayItemsByKeys,
static fn (array $arrayItems): bool => count($arrayItems) > 1
);
$result = [];
foreach ($arrayItemsByKeys as $arrayItems) {
if (count($arrayItems) <= 1) {
continue;
}

$currentArrayItem = current($arrayItems);
/** @var Expr $currentArrayItemKey */
$currentArrayItemKey = $currentArrayItem->key;

if ($this->multiInstanceofChecker->isInstanceOf($currentArrayItemKey, self::ALLOWED_KEY_DUPLICATES)) {
continue;
}

$result[] = $arrayItems;
}

return array_filter($arrayItemsByKeys, static fn (array $arrayItems): bool => count($arrayItems) > 1);
return $result;
}
}

0 comments on commit 5ea7727

Please sign in to comment.