ソースを参照

Changed CollectionTrait::shuffle() to return all elements in collection.

Corey Taylor 5 年 前
コミット
faf5d574f0

+ 3 - 2
src/Collection/CollectionInterface.php

@@ -789,7 +789,8 @@ interface CollectionInterface extends Iterator, JsonSerializable
     public function toList(): array;
 
     /**
-     * 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.
      *
@@ -1145,7 +1146,7 @@ interface CollectionInterface extends Iterator, JsonSerializable
     public function count(): int;
 
     /**
-     * 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

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

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

@@ -925,6 +925,20 @@ 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->assertContainsEquals(1, $result);
+        $this->assertContainsEquals(2, $result);
+    }
+
+    /**
      * Tests sample
      *
      * @dataProvider simpleProvider