From 43851636c4b5bf87ea81f6bfb108bc14db445446 Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Sun, 11 Mar 2018 21:59:59 +1100 Subject: [PATCH 1/2] add seed to Arr::shuffle() --- src/Illuminate/Support/Arr.php | 13 +++++++++++-- src/Illuminate/Support/Collection.php | 14 +------------- tests/Support/SupportArrTest.php | 8 ++++++++ 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/Illuminate/Support/Arr.php b/src/Illuminate/Support/Arr.php index 5edda9ba9820..51d949ab7e98 100755 --- a/src/Illuminate/Support/Arr.php +++ b/src/Illuminate/Support/Arr.php @@ -541,11 +541,20 @@ public static function set(&$array, $key, $value) * Shuffle the given array and return the result. * * @param array $array + * @param int $seed * @return array */ - public static function shuffle($array) + public static function shuffle($array, $seed = null) { - shuffle($array); + if (is_null($seed)) { + shuffle($array); + } else { + srand($seed); + + usort($array, function () { + return rand(-1, 1); + }); + } return $array; } diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index a20d39d5d894..86dbacd23eee 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1360,19 +1360,7 @@ public function shift() */ public function shuffle($seed = null) { - $items = $this->items; - - if (is_null($seed)) { - shuffle($items); - } else { - srand($seed); - - usort($items, function () { - return rand(-1, 1); - }); - } - - return new static($items); + return new static(Arr::shuffle($this->items, $seed)); } /** diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index d62da7359398..59f0cc4c404c 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -498,6 +498,14 @@ public function testSet() $this->assertEquals(['products' => ['desk' => ['price' => 200]]], $array); } + public function testShuffleWithSeed() + { + $this->assertEquals( + Arr::shuffle(range(0, 100, 10), 1234), + Arr::shuffle(range(0, 100, 10), 1234) + ); + } + public function testSort() { $unsorted = [ From 91ee51fefc510f2ed20701579e9d6b40abaf82d6 Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Sun, 11 Mar 2018 22:47:38 +1100 Subject: [PATCH 2/2] update doc block --- src/Illuminate/Support/Arr.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Support/Arr.php b/src/Illuminate/Support/Arr.php index 51d949ab7e98..616c030c5fe3 100755 --- a/src/Illuminate/Support/Arr.php +++ b/src/Illuminate/Support/Arr.php @@ -541,7 +541,7 @@ public static function set(&$array, $key, $value) * Shuffle the given array and return the result. * * @param array $array - * @param int $seed + * @param int|null $seed * @return array */ public static function shuffle($array, $seed = null)