From 9a6ca3a91a1e846400226b398f92c86a1db80024 Mon Sep 17 00:00:00 2001 From: Sebastian De Deyne Date: Tue, 20 Dec 2016 15:06:44 +0100 Subject: [PATCH] Always return a collection when calling Collection::random with a parameter (#16865) --- src/Illuminate/Support/Collection.php | 8 ++++++-- tests/Support/SupportCollectionTest.php | 15 ++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 5b7ae3e6d97..db19e2d2121 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -892,7 +892,7 @@ public function put($key, $value) /** * Get one or more items randomly from the collection. * - * @param int $amount + * @param int|null $amount * @return mixed * * @throws \InvalidArgumentException @@ -905,10 +905,14 @@ public function random($amount = 1) $keys = array_rand($this->items, $amount); - if ($amount == 1) { + if (count(func_get_args()) == 0) { return $this->items[$keys]; } + if (! is_array($keys)) { + $keys = [$keys]; + } + return new static(array_intersect_key($this->items, array_flip($keys))); } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index fa3e8897b6d..8cf6d456ed8 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -814,15 +814,24 @@ public function testRandom() { $data = new Collection([1, 2, 3, 4, 5, 6]); - $random = $data->random(); - $this->assertInternalType('integer', $random); - $this->assertContains($random, $data->all()); + $random = $data->random(1); + $this->assertInstanceOf(Collection::class, $random); + $this->assertCount(1, $random); $random = $data->random(3); $this->assertInstanceOf(Collection::class, $random); $this->assertCount(3, $random); } + public function testRandomWithoutArgument() + { + $data = new Collection([1, 2, 3, 4, 5, 6]); + + $random = $data->random(); + $this->assertInternalType('integer', $random); + $this->assertContains($random, $data->all()); + } + /** * @expectedException InvalidArgumentException */