Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Php85\Rector\ArrayDimFetch\ArrayFirstLastRector\Fixture;

final class SkipAsNestedAssign
{
public function run(array $result, $lastInsertedId)
{
$result[\array_key_last($result)]['id'] = $lastInsertedId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\Php85\Rector\ArrayDimFetch\ArrayFirstLastRector\Fixture;

final class SkipAsNestedAssignOp
{
public function run(array $result, $lastInsertedId)
{
$result[\array_key_last($result)][0] += $lastInsertedId;
}
}
19 changes: 18 additions & 1 deletion src/PhpParser/NodeVisitor/AssignedToNodeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use PhpParser\Node;
use PhpParser\Node\ArrayItem;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Expr\AssignRef;
Expand All @@ -22,7 +24,7 @@ final class AssignedToNodeVisitor extends NodeVisitorAbstract implements Decorat
public function enterNode(Node $node): ?Node
{
if ($node instanceof AssignOp) {
$node->var->setAttribute(AttributeKey::IS_ASSIGN_OP_VAR, true);
$this->markAssignOpVar($node->var);
return null;
}

Expand Down Expand Up @@ -54,4 +56,19 @@ public function enterNode(Node $node): ?Node

return null;
}

/**
* Marks the whole dim fetch chain, not just the outermost node: $array[$key][0] += 1 writes
* to $array[$key] as well, so a rule that rewrites the inner fetch would change a write
* into a read of a temporary value.
*/
private function markAssignOpVar(Expr $expr): void
{
$expr->setAttribute(AttributeKey::IS_ASSIGN_OP_VAR, true);

while ($expr instanceof ArrayDimFetch) {
$expr = $expr->var;
$expr->setAttribute(AttributeKey::IS_ASSIGN_OP_VAR, true);
}
}
}