Browse Source

Making Collection::toArray() drop the keys when dealing with RecursiveIterator

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.
Jose Lorenzo Rodriguez 10 years ago
parent
commit
394e741c5c

+ 3 - 0
src/Collection/CollectionTrait.php

@@ -470,6 +470,9 @@ trait CollectionTrait
             $items = $iterator->getArrayCopy();
             return $preserveKeys ? $items : array_values($items);
         }
+        if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
+            $preserveKeys = false;
+        }
         return iterator_to_array($this, $preserveKeys);
     }
 

+ 2 - 1
tests/TestCase/Collection/CollectionTest.php

@@ -1409,7 +1409,7 @@ class CollectionTest extends TestCase
         ];
 
         $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 = [
             [
@@ -1444,6 +1444,7 @@ class CollectionTest extends TestCase
         ];
         $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());
     }