Browse Source

Merge pull request #14767 from cakephp/backport-14763

3.x - Changed CollectionTrait::shuffle() to return all elements in collection.
Mark Story 5 years ago
parent
commit
ffb1ba3c41

+ 3 - 2
src/Collection/CollectionInterface.php

@@ -761,7 +761,8 @@ interface CollectionInterface extends Iterator, JsonSerializable
     public function toList();
 
     /**
-     * Convert a result set into JSON.
+     * Returns the data that can be converted to JSON. This returns the same data
+     * as `toArray()` which contains only unique keys.
      *
      * Part of JsonSerializable interface.
      *
@@ -1117,7 +1118,7 @@ interface CollectionInterface extends Iterator, JsonSerializable
     public function count();
 
     /**
-     * Returns the number of unique keys in this iterator. This is, the number of
+     * Returns the number of unique keys in this iterator. This is the same as the number of
      * elements the collection will contain after calling `toArray()`
      *
      * This method comes with a number of caveats. Please refer to `CollectionInterface::count()`

+ 1 - 1
src/Collection/CollectionTrait.php

@@ -331,7 +331,7 @@ trait CollectionTrait
      */
     public function shuffle()
     {
-        $elements = $this->toArray();
+        $elements = $this->toList();
         shuffle($elements);
 
         return $this->newCollection($elements);

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

@@ -981,6 +981,21 @@ class CollectionTest extends TestCase
     }
 
     /**
+     * Tests shuffle with duplicate keys.
+     *
+     * @return void
+     */
+    public function testShuffleDuplicateKeys()
+    {
+        $collection = (new Collection(['a' => 1]))->append(['a' => 2])->shuffle();
+        $result = $collection->toArray();
+        $this->assertCount(2, $result);
+        $this->assertEquals([0, 1], array_keys($result));
+        $this->assertContains(1, $result);
+        $this->assertContains(2, $result);
+    }
+
+    /**
      * Tests sample
      *
      * @dataProvider simpleProvider