Fix non-direct parent foreach in ForeachItemsAssignToEmptyArrayToAssignRector

This commit is contained in:
TomasVotruba 2020-01-08 15:03:09 +01:00
parent 4cbaf5f3ef
commit cdf2fb35a4
2 changed files with 56 additions and 4 deletions

View File

@ -131,19 +131,32 @@ PHP
});
}
private function findPreviousNodeUsageInForeach(Node $node, Expr $expr): ?Node
{
return $this->betterNodeFinder->findFirstPrevious($node, function (Node $node) use ($expr) {
if ($node === $expr) {
return false;
}
if (! $this->areNodesEqual($node, $expr)) {
return false;
}
return $node->getAttribute(AttributeKey::PARENT_NODE) instanceof Foreach_;
});
}
private function shouldSkipAsPartOfNestedForeach(Foreach_ $foreach): bool
{
$previousForeachVariableUsage = $this->findPreviousNodeUsage($foreach, $foreach->expr);
$previousForeachVariableUsage = $this->findPreviousNodeUsageInForeach($foreach, $foreach->expr);
if ($previousForeachVariableUsage === null) {
return false;
}
/** @var Foreach_ $previousForeachVariableUsageParentNode */
$previousForeachVariableUsageParentNode = $previousForeachVariableUsage->getAttribute(
AttributeKey::PARENT_NODE
);
if (! $previousForeachVariableUsageParentNode instanceof Foreach_) {
return false;
}
return $this->areNodesEqual($previousForeachVariableUsageParentNode->valueVar, $foreach->expr);
}

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Tests\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector\Fixture;
final class RemoveMutualCheckersCompilerPass
{
/**
* List of checkers with the same functionality.
* If found, only the first one is used.
*
* @var string[][]
*/
private static $duplicatedCheckerGroups = [
[
'SlevomatCodingStandard\Sniffs\Namespaces\ReferenceUsedNamesOnlySniff',
'Symplify\CodingStandard\Sniffs\Namespaces\ClassNamesWithoutPreSlashSniff',
],
];
/**
* @param string[] $checkers
* @return string[]
*/
public function resolveCheckersToRemove(array $checkers): array
{
$checkersToRemove = [];
foreach (self::$duplicatedCheckerGroups as $matchingCheckerGroup) {
if ($matchingCheckerGroup === []) {
continue;
}
foreach ($matchingCheckerGroup as $checkerToRemove) {
$checkersToRemove[] = $checkerToRemove;
}
}
}
}