Skip to content

Commit

Permalink
Allow missing elements when destructuring arrays in foreach loops (#1880
Browse files Browse the repository at this point in the history
)

* Allow missing elements when destructuring arrays in foreach loops

* Delete an unused import

* Move the check to `canMutate`
  • Loading branch information
MidnightDesign authored Oct 9, 2023
1 parent 3dc7cce commit 2789fdd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Mutator/Removal/ArrayItemRemoval.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayItem;
use function range;
use Webmozart\Assert\Assert;

/**
* @internal
Expand Down Expand Up @@ -116,8 +115,6 @@ public static function getDefinition(): ?Definition
*/
public function mutate(Node $node): iterable
{
Assert::allNotNull($node->items);

foreach ($this->getItemsIndexes($node->items) as $indexToRemove) {
$newArrayNode = clone $node;
unset($newArrayNode->items[$indexToRemove]);
Expand Down Expand Up @@ -147,13 +144,18 @@ public function canMutate(Node $node): bool
return false;
}

// Don't mutate destructured values in foreach loops
if ($parent instanceof Node\Stmt\Foreach_ && $parent->valueVar === $node) {
return false;
}

return true;
}

/**
* @psalm-mutation-free
*
* @param ArrayItem[] $items
* @param array<array-key, ArrayItem|null> $items
*
* @return int[]
*/
Expand Down
4 changes: 4 additions & 0 deletions tests/phpunit/Mutator/Removal/ArrayItemRemovalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,9 @@ public function mutationsProvider(): iterable
yield 'It does not mutate arrays as an attribute argument' => [
MutatorFixturesProvider::getFixtureFileContent($this, 'does-not-mutate-array-in-attribute.php'),
];

yield 'It does not mutate destructured array values in foreach loops' => [
'<?php foreach ($items as [, $value]) {}',
];
}
}

0 comments on commit 2789fdd

Please sign in to comment.