Skip to content

Commit

Permalink
Making Collection::toArray() drop the keys when dealing with Recursiv…
Browse files Browse the repository at this point in the history
…eIterator

I could not think of a falid case where losing data when converting to array
was a desirable outcome. I fact this was a reason for a lot of hair-pulling
situations and made it really difficult to explain certain collection features
to some people.

This new behavior makes more sense for the great majority of cases and reduces
the risk of creating new bugs.
  • Loading branch information
lorenzo committed Nov 7, 2015
1 parent 8a7e54c commit 394e741
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/Collection/CollectionTrait.php
Expand Up @@ -470,6 +470,9 @@ public function toArray($preserveKeys = true)
$items = $iterator->getArrayCopy();
return $preserveKeys ? $items : array_values($items);
}
if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
$preserveKeys = false;
}
return iterator_to_array($this, $preserveKeys);
}

Expand Down
3 changes: 2 additions & 1 deletion tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1409,7 +1409,7 @@ public function testUnfoldedExtract()
];

$extracted = (new Collection($items))->extract('comments.{*}.id');
$this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toList());
$this->assertEquals([1, 2, 3, 4, 7, null], $extracted->toArray());

$items = [
[
Expand Down Expand Up @@ -1444,6 +1444,7 @@ public function testUnfoldedExtract()
];
$extracted = (new Collection($items))->extract('comments.{*}.voters.{*}.id');
$expected = [1, 2, 3, 4, 5, null, 6];
$this->assertEquals($expected, $extracted->toArray());
$this->assertEquals($expected, $extracted->toList());
}

Expand Down

0 comments on commit 394e741

Please sign in to comment.