[Naming] Various Improve RenameForeachValueVariableToMatchExprVariableRector (#5682)

Co-authored-by: kaizen-ci <info@kaizen-ci.org>
This commit is contained in:
Abdul Malik Ikhsan 2021-02-27 18:32:42 +07:00 committed by GitHub
parent c7b76c4983
commit 3bb327e797
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 63 additions and 4 deletions

View File

@ -6,6 +6,7 @@ namespace Rector\Naming\Rector\Foreach_;
use Doctrine\Inflector\Inflector;
use PhpParser\Node;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\Rector\AbstractRector;
@ -78,6 +79,10 @@ CODE_SAMPLE
*/
public function refactor(Node $node): ?Node
{
if (! $node->expr instanceof Variable && ! $node->expr instanceof PropertyFetch) {
return null;
}
$exprName = $this->getName($node->expr);
if ($exprName === null) {
return null;
@ -91,15 +96,20 @@ CODE_SAMPLE
$singularValueVarName = $this->inflector->singularize($exprName);
$singularValueVarName = $singularValueVarName === $exprName
? 'single' . ucfirst($singularValueVarName)
? 'single' . ucfirst(ltrim($singularValueVarName, 'single'))
: $singularValueVarName;
if ($this->shouldSkip($keyVarName, $valueVarName, $singularValueVarName, $node)) {
return null;
}
$node->valueVar = new Variable($singularValueVarName);
$this->traverseNodesWithCallable($node->stmts, function (Node $node) use (
return $this->processRename($node, $valueVarName, $singularValueVarName);
}
private function processRename(Foreach_ $foreach, string $valueVarName, string $singularValueVarName): Foreach_
{
$foreach->valueVar = new Variable($singularValueVarName);
$this->traverseNodesWithCallable($foreach->stmts, function (Node $node) use (
$singularValueVarName,
$valueVarName
): ?Variable {
@ -113,7 +123,7 @@ CODE_SAMPLE
return new Variable($singularValueVarName);
});
return $node;
return $foreach;
}
private function shouldSkip(

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\Naming\Tests\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector\Fixture;
class SkipAlreadyPrefixedSingle
{
public function run()
{
foreach ($singleTypesAsString as $key => $singleTypeAsString) {
$singleTypesAsString[$key] = $singleTypeAsString . '[]';
}
}
}
?>

View File

@ -0,0 +1,18 @@
<?php
namespace Rector\Naming\Tests\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector\Fixture;
class SkipClassConstant
{
private const A_CONSTANTS = [];
public function run()
{
$array = [];
foreach (self::A_CONSTANTS as $property) {
$array[] = $property;
}
}
}
?>

View File

@ -0,0 +1,16 @@
<?php
namespace Rector\Naming\Tests\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector\Fixture;
class SkipMethodCall
{
public function run()
{
$array = [];
foreach ($this->calls() as $property) {
$array[] = $property;
}
}
}
?>