Skip to content

Commit

Permalink
ArrayItemRemoval should not mutate lists (#1358)
Browse files Browse the repository at this point in the history
* ArrayItemRemoval should not mutate lists

* Update src/Mutator/Removal/ArrayItemRemoval.php

* Update src/Mutator/Removal/ArrayItemRemoval.php
  • Loading branch information
sanmai authored and maks-rafalko committed Oct 21, 2020
1 parent ddea14c commit 7eb647d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/Mutator/Removal/ArrayItemRemoval.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Infection\Mutator\GetConfigClassName;
use Infection\Mutator\GetMutatorName;
use Infection\Mutator\MutatorCategory;
use Infection\PhpParser\Visitor\ParentConnector;
use function min;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayItem;
Expand Down Expand Up @@ -119,7 +120,22 @@ public function mutate(Node $arrayNode): iterable

public function canMutate(Node $node): bool
{
return $node instanceof Node\Expr\Array_ && count($node->items);
if (!$node instanceof Node\Expr\Array_) {
return false;
}

if ($node->items === []) {
return false;
}

$parent = ParentConnector::findParent($node);

// Arrays to the left of an assignments are not arrays but lists.
if ($parent instanceof Node\Expr\Assign && $parent->var === $node) {
return false;
}

return true;
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/phpunit/Mutator/Removal/ArrayItemRemovalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,5 +102,17 @@ public function mutationsProvider(): iterable
],
['remove' => 'all', 'limit' => 1],
];

yield 'It does not mutate lists with missing elements' => [
'<?php [, $a] = [];',
];

yield 'It does not mutate lists with one element' => [
'<?php [$a] = [];',
];

yield 'It does not mutate lists with any number of elements' => [
'<?php [$a, $b] = [];',
];
}
}

0 comments on commit 7eb647d

Please sign in to comment.