Browse Source

Preserve keys option on Collection::chunk

Joris Vaesen 9 years ago
parent
commit
a4cbd70aae

+ 2 - 1
src/Collection/CollectionInterface.php

@@ -915,9 +915,10 @@ interface CollectionInterface extends Iterator, JsonSerializable
      * ```
      *
      * @param int $chunkSize The maximum size for each chunk
+     * @param boolean $preserveKeys If the keys of the array should be preserved
      * @return \Cake\Collection\CollectionInterface
      */
-    public function chunk($chunkSize);
+    public function chunk($chunkSize, $preserveKeys = false);
 
     /**
      * Returns whether or not there are elements in this collection

+ 12 - 4
src/Collection/CollectionTrait.php

@@ -627,16 +627,24 @@ trait CollectionTrait
      * {@inheritDoc}
      *
      */
-    public function chunk($chunkSize)
+    public function chunk($chunkSize, $preserveKeys = false)
     {
-        return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
-            $values = [$v];
+        return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
+            $key = 0;
+            if ($preserveKeys) {
+                $key = $k;
+            }
+            $values = [$key => $v];
             for ($i = 1; $i < $chunkSize; $i++) {
                 $iterator->next();
                 if (!$iterator->valid()) {
                     break;
                 }
-                $values[] = $iterator->current();
+                if ($preserveKeys) {
+                    $values[$iterator->key()] = $iterator->current();
+                } else {
+                    $values[] = $iterator->current();
+                }
             }
 
             return $values;

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

@@ -1771,6 +1771,19 @@ class CollectionTest extends TestCase
     }
 
     /**
+     * Tests the chunk method with preserved keys
+     *
+     * @return void
+     */
+    public function testChunkPreserveKeys()
+    {
+        $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
+        $chunked = $collection->chunk(2, true)->toList();
+        $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
+        $this->assertEquals($expected, $chunked);
+    }
+
+    /**
      * Tests cartesianProduct
      *
      * @return void
@@ -1961,4 +1974,17 @@ class CollectionTest extends TestCase
 
         $collection->transpose();
     }
+
+    /**
+     * Tests the chunk method with preserved keys
+     *
+     * @return void
+     */
+    public function testChunkPreserveKeys()
+    {
+        $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
+        $chunked = $collection->chunk(2, true)->toList();
+        $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
+        $this->assertEquals($expected, $chunked);
+    }
 }