Skip to content

Commit

Permalink
[CodeQuality] Skip re use variable in assign Expr on InlineArrayRetur…
Browse files Browse the repository at this point in the history
…nAssignRector (#2325)

* [CodeQuality] Skip re use variable in assign Expr on InlineArrayReturnAssignRector

* Fixed 🎉

* [ci-review] Rector Rectify

* final touch: move check for reuse

* matchKeyOnArrayDimFetchOfVariable never reuse

Co-authored-by: GitHub Action <action@github.com>
  • Loading branch information
samsonasik and actions-user committed May 18, 2022
1 parent 15d93fa commit 50943ea
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\InlineArrayReturnAssignRector\Fixture;

final class SkipReuseVariableInAssignExpr
{
public function run()
{
$continuation = [];
$continuation['descriptions'] = ['a'];
$continuation['descriptions'] = \array_map(function ($description) {
$description = 'b';
return $description;
}, $continuation['descriptions']);

return $continuation;
}
}
16 changes: 14 additions & 2 deletions rules/CodeQuality/NodeAnalyzer/VariableDimFetchAssignResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Rector\CodeQuality\NodeAnalyzer;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
Expand All @@ -12,11 +13,13 @@
use PhpParser\Node\Stmt\Expression;
use Rector\CodeQuality\ValueObject\KeyAndExpr;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;

final class VariableDimFetchAssignResolver
{
public function __construct(
private readonly NodeComparator $nodeComparator
private readonly NodeComparator $nodeComparator,
private readonly BetterNodeFinder $betterNodeFinder
) {
}

Expand Down Expand Up @@ -51,7 +54,7 @@ public function resolveFromStmtsAndVariable(array $stmts, Variable $variable): a
return $keysAndExprs;
}

public function matchKeyOnArrayDimFetchOfVariable(Assign $assign, Variable $variable): ?Expr
private function matchKeyOnArrayDimFetchOfVariable(Assign $assign, Variable $variable): ?Expr
{
if (! $assign->var instanceof ArrayDimFetch) {
return null;
Expand All @@ -62,6 +65,15 @@ public function matchKeyOnArrayDimFetchOfVariable(Assign $assign, Variable $vari
return null;
}

$isFoundInExpr = (bool) $this->betterNodeFinder->findFirst(
$assign->expr,
fn (Node $subNode): bool => $this->nodeComparator->areNodesEqual($subNode, $variable)
);

if ($isFoundInExpr) {
return null;
}

return $arrayDimFetch->dim;
}
}

0 comments on commit 50943ea

Please sign in to comment.