[DowngradePhp71] Add DowngradeKeysInListRector (#6170)

Co-authored-by: kaizen-ci <info@kaizen-ci.org>
This commit is contained in:
Abdul Malik Ikhsan 2021-04-20 19:21:02 +07:00 committed by GitHub
parent deafaf9ecd
commit cd3725aeb5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 686 additions and 34 deletions

View File

@ -8,6 +8,7 @@ use Rector\DowngradePhp71\Rector\Array_\SymmetricArrayDestructuringToListRector;
use Rector\DowngradePhp71\Rector\ClassConst\DowngradeClassConstantVisibilityRector;
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeNullableTypeDeclarationRector;
use Rector\DowngradePhp71\Rector\FunctionLike\DowngradeVoidTypeDeclarationRector;
use Rector\DowngradePhp71\Rector\List_\DowngradeKeysInListRector;
use Rector\DowngradePhp71\Rector\String_\DowngradeNegativeStringOffsetToStrlenRector;
use Rector\DowngradePhp71\Rector\TryCatch\DowngradePipeToMultiCatchExceptionRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
@ -23,4 +24,5 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$services->set(DowngradePipeToMultiCatchExceptionRector::class);
$services->set(SymmetricArrayDestructuringToListRector::class);
$services->set(DowngradeNegativeStringOffsetToStrlenRector::class);
$services->set(DowngradeKeysInListRector::class);
};

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class DowngradeKeysInListRectorTest 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';
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValue
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as list("id" => $id1, "name" => $name1)) {
}
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValue
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as $singleData) {
$id1 = $singleData["id"];
$name1 = $singleData["name"];
}
}
}
?>

View File

@ -0,0 +1,41 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValue2
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as list("id" => $id1, "name" => $name1)) {
echo 'statement';
}
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValue2
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as $singleData) {
$id1 = $singleData["id"];
$name1 = $singleData["name"];
echo 'statement';
}
}
}
?>

View File

@ -0,0 +1,39 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValueKeyedArray
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as ["id" => $id1, "name" => $name1]) {
}
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValueKeyedArray
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as $singleData) {
$id1 = $singleData["id"];
$name1 = $singleData["name"];
}
}
}
?>

View File

@ -0,0 +1,41 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValueUsed
{
public function run($singleData): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as list("id" => $id1, "name" => $name1)) {
echo $singleData;
}
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class AsForeachValueUsed
{
public function run($singleData): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as $singleData1) {
$id1 = $singleData1["id"];
$name1 = $singleData1["name"];
echo $singleData;
}
}
}
?>

View File

@ -0,0 +1,36 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class Fixture
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
list("id" => $id1, "name" => $name1) = $data[0];
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class Fixture
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
$id1 = $data[0]["id"];
$name1 = $data[0]["name"];
}
}
?>

View File

@ -0,0 +1,38 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class MirrorComments
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
// a comment
list("id" => $id1, "name" => $name1) = $data[0];
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class MirrorComments
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
// a comment
$id1 = $data[0]["id"];
$name1 = $data[0]["name"];
}
}
?>

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class SkipNotKeysInList
{
public function run(): void
{
$data = ['foo', 'bar', 'baz'];
list($foo, $bar, $baz) = $data;
}
}
?>

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class SkipNotKeysInList2
{
public function run(): void
{
$data = ['foo', 'bar', 'baz'];
list(, $bar, $baz) = $data;
}
}
?>

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class SkipNotKeysInList3
{
public function run(): void
{
$data = ['foo', 'bar', 'baz'];
list($bar, $baz, ) = $data;
}
}
?>

View File

@ -0,0 +1,36 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class UseKeyedArray
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
["id" => $id1, "name" => $name1] = $data[0];
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class UseKeyedArray
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
$id1 = $data[0]["id"];
$name1 = $data[0]["name"];
}
}
?>

View File

@ -0,0 +1,36 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class VariableKey
{
public function run($id = 'id', $name = 'name'): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
list($id => $id1, $name => $name1) = $data[0];
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class VariableKey
{
public function run($id = 'id', $name = 'name'): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
$id1 = $data[0][$id];
$name1 = $data[0][$name];
}
}
?>

View File

@ -0,0 +1,41 @@
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class VariableKeyInForeachValue
{
public function run($id = 'id', $name = 'name'): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as list($id => $id1, $name => $name1)) {
echo 'statement';
}
}
}
?>
-----
<?php
namespace Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\Fixture;
class VariableKeyInForeachValue
{
public function run($id = 'id', $name = 'name'): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as $singleData) {
$id1 = $singleData[$id];
$name1 = $singleData[$name];
echo 'statement';
}
}
}
?>

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
use Rector\DowngradePhp71\Rector\List_\DowngradeKeysInListRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(DowngradeKeysInListRector::class);
};

View File

@ -13,6 +13,7 @@ use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser;
@ -38,16 +39,23 @@ final class ForeachAnalyzer
*/
private $simpleCallableNodeTraverser;
/**
* @var BetterNodeFinder
*/
private $betterNodeFinder;
public function __construct(
NodeComparator $nodeComparator,
ForAnalyzer $forAnalyzer,
NodeNameResolver $nodeNameResolver,
SimpleCallableNodeTraverser $simpleCallableNodeTraverser
SimpleCallableNodeTraverser $simpleCallableNodeTraverser,
BetterNodeFinder $betterNodeFinder
) {
$this->nodeComparator = $nodeComparator;
$this->forAnalyzer = $forAnalyzer;
$this->nodeNameResolver = $nodeNameResolver;
$this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser;
$this->betterNodeFinder = $betterNodeFinder;
}
/**
@ -124,4 +132,31 @@ final class ForeachAnalyzer
}
);
}
public function isValueVarUsed(Foreach_ $foreach, string $singularValueVarName): bool
{
$isUsedInStmts = (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (Node $node) use (
$singularValueVarName
): bool {
if (! $node instanceof Variable) {
return false;
}
return $this->nodeNameResolver->isName($node, $singularValueVarName);
});
if ($isUsedInStmts) {
return true;
}
return (bool) $this->betterNodeFinder->findFirstNext($foreach, function (Node $node) use (
$singularValueVarName
): bool {
if (! $node instanceof Variable) {
return false;
}
return $this->nodeNameResolver->isName($node, $singularValueVarName);
});
}
}

View File

@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Rector\DowngradePhp71\Rector\List_;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\List_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use Rector\CodeQuality\NodeAnalyzer\ForeachAnalyzer;
use Rector\Core\Rector\AbstractRector;
use Rector\Naming\ExpectedNameResolver\InflectorSingularResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\DowngradePhp71\Rector\List_\DowngradeKeysInListRector\DowngradeKeysInListRectorTest
*/
final class DowngradeKeysInListRector extends AbstractRector
{
/**
* @var InflectorSingularResolver
*/
private $inflectorSingularResolver;
/**
* @var ForeachAnalyzer
*/
private $foreachAnalyzer;
public function __construct(InflectorSingularResolver $inflectorSingularResolver, ForeachAnalyzer $foreachAnalyzer)
{
$this->inflectorSingularResolver = $inflectorSingularResolver;
$this->foreachAnalyzer = $foreachAnalyzer;
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [List_::class, Array_::class];
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Extract keys in list to its own variable assignment',
[
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
list("id" => $id1, "name" => $name1) = $data[0];
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run(): void
{
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
$id1 = $data[0]["id"];
$name1 = $data[0]["name"];
}
}
CODE_SAMPLE
),
]
);
}
/**
* @param List_|Array_ $node
*/
public function refactor(Node $node): ?Node
{
$parent = $node->getAttribute(AttributeKey::PARENT_NODE);
if (! $parent instanceof Node) {
return null;
}
$parentExpression = $parent->getAttribute(AttributeKey::PARENT_NODE);
if (! $parentExpression instanceof Node) {
return null;
}
$assignExpressions = $this->processExtractToItsOwnVariable($node, $parent, $parentExpression);
if ($assignExpressions === []) {
return null;
}
if ($parent instanceof Assign) {
$this->mirrorComments($assignExpressions[0], $parentExpression);
$this->addNodesBeforeNode($assignExpressions, $node);
$this->removeNode($parentExpression);
return $node;
}
if ($parent instanceof Foreach_) {
$newValueVar = $this->getNewValueVar($parent);
$parent->valueVar = new Variable($newValueVar);
$stmts = $parent->stmts;
if ($stmts === []) {
$parent->stmts = $assignExpressions;
} else {
$this->addNodesBeforeNode($assignExpressions, $parent->stmts[0]);
}
return $parent->valueVar;
}
return null;
}
/**
* @param List_|Array_ $node
* @return Expression[]
*/
private function processExtractToItsOwnVariable(Node $node, Node $parent, Node $parentExpression): array
{
$items = $node->items;
$assignExpressions = [];
foreach ($items as $item) {
if (! $item instanceof ArrayItem) {
return [];
}
/** keyed and not keyed cannot be mixed, return early */
if (! $item->key instanceof Expr) {
return [];
}
if ($parentExpression instanceof Expression && $parent instanceof Assign && $parent->var === $node) {
$assignExpressions[] = new Expression(
new Assign($item->value, new ArrayDimFetch($parent->expr, $item->key))
);
}
if (! $parent instanceof Foreach_) {
continue;
}
if ($parent->valueVar !== $node) {
continue;
}
$assignExpressions[] = $this->getExpressionFromForeachValue($parent, $item);
}
return $assignExpressions;
}
private function getExpressionFromForeachValue(Foreach_ $foreach, ArrayItem $arrayItem): Expression
{
$newValueVar = $this->getNewValueVar($foreach);
$assign = new Assign($arrayItem->value, new ArrayDimFetch(new Variable($newValueVar), $arrayItem->key));
return new Expression($assign);
}
private function getNewValueVar(Foreach_ $foreach, ?string $newValueVar = null): string
{
if ($newValueVar === null) {
$newValueVar = $this->inflectorSingularResolver->resolve((string) $this->getName($foreach->expr));
}
$count = 0;
if ($this->foreachAnalyzer->isValueVarUsed($foreach, $newValueVar)) {
$newValueVar .= (string) ++$count;
return $this->getNewValueVar($foreach, $newValueVar);
}
return $newValueVar;
}
}

View File

@ -10,6 +10,7 @@ use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Foreach_;
use PHPStan\Type\ThisType;
use Rector\CodeQuality\NodeAnalyzer\ForeachAnalyzer;
use Rector\Core\Rector\AbstractRector;
use Rector\Naming\ExpectedNameResolver\InflectorSingularResolver;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
@ -25,9 +26,15 @@ final class RenameForeachValueVariableToMatchExprVariableRector extends Abstract
*/
private $inflectorSingularResolver;
public function __construct(InflectorSingularResolver $inflectorSingularResolver)
/**
* @var ForeachAnalyzer
*/
private $foreachAnalyzer;
public function __construct(InflectorSingularResolver $inflectorSingularResolver, ForeachAnalyzer $foreachAnalyzer)
{
$this->inflectorSingularResolver = $inflectorSingularResolver;
$this->foreachAnalyzer = $foreachAnalyzer;
}
public function getRuleDefinition(): RuleDefinition
@ -89,6 +96,7 @@ CODE_SAMPLE
if ($exprName === null) {
return null;
}
if ($node->keyVar instanceof Node) {
return null;
}
@ -102,8 +110,11 @@ CODE_SAMPLE
if ($singularValueVarName === $exprName) {
return null;
}
if ($singularValueVarName === $valueVarName) {
return null;
}
if ($this->shouldSkip($valueVarName, $singularValueVarName, $node)) {
if ($this->foreachAnalyzer->isValueVarUsed($node, $singularValueVarName)) {
return null;
}
@ -139,35 +150,4 @@ CODE_SAMPLE
return $foreach;
}
private function shouldSkip(string $valueVarName, string $singularValueVarName, Foreach_ $foreach): bool
{
if ($singularValueVarName === $valueVarName) {
return true;
}
$isUsedInStmts = (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (Node $node) use (
$singularValueVarName
): bool {
if (! $node instanceof Variable) {
return false;
}
return $this->isName($node, $singularValueVarName);
});
if ($isUsedInStmts) {
return true;
}
return (bool) $this->betterNodeFinder->findFirstNext($foreach, function (Node $node) use (
$singularValueVarName
): bool {
if (! $node instanceof Variable) {
return false;
}
return $this->isName($node, $singularValueVarName);
});
}
}