Browse Source

Merge pull request #5569 from cakephp/3.0-collection-toList

Implemented Collection::toList() to avoid confusion when getting results
Mark Story 11 years ago
parent
commit
61699baeb6

+ 9 - 0
src/Collection/CollectionInterface.php

@@ -625,6 +625,7 @@ interface CollectionInterface extends Iterator, JsonSerializable
      * @return \Cake\Collection\CollectionInterface
      */
     public function insert($path, $values);
+
     /**
      * Returns an array representation of the results
      *
@@ -637,6 +638,14 @@ interface CollectionInterface extends Iterator, JsonSerializable
     public function toArray($preserveKeys = true);
 
     /**
+     * Returns an numerically-indexed array representation of the results.
+     * This is equivalent to calling `toArray(false)`
+     *
+     * @return array
+     */
+    public function toList();
+
+    /**
      * Convert a result set into JSON.
      *
      * Part of JsonSerializable interface.

+ 9 - 0
src/Collection/CollectionTrait.php

@@ -418,6 +418,15 @@ trait CollectionTrait
      * {@inheritDoc}
      *
      */
+    public function toList()
+    {
+        return iterator_to_array($this, false);
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     */
     public function jsonSerialize()
     {
         return $this->toArray();

+ 12 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -529,6 +529,18 @@ class CollectionTest extends TestCase
     }
 
     /**
+     * Test toList method
+     *
+     * @return void
+     */
+    public function testToList()
+    {
+        $data = [100 => 1, 300 => 2, 500 => 3, 1 => 4];
+        $collection = new Collection($data);
+        $this->assertEquals(array_values($data), $collection->toList());
+    }
+
+    /**
      * Test json enconding
      *
      * @return void