Skip to content

Commit 8053238

Browse files
browner12taylorotwell
authored andcommitted
fix for requesting 0 randoms on empty collection (#20402)
previously if you requested 0 random items from an empty collection, it would mistakedly think we were requesting 1 item. this commit moves the check for a request of zero random items to the beginning, so we don't run into this issue. also add a test.
1 parent f20a5ea commit 8053238

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/Illuminate/Support/Collection.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,6 +1079,10 @@ public function put($key, $value)
10791079
*/
10801080
public function random($amount = null)
10811081
{
1082+
if ($amount === 0) {
1083+
return new static;
1084+
}
1085+
10821086
if (($requested = $amount ?: 1) > ($count = $this->count())) {
10831087
throw new InvalidArgumentException(
10841088
"You requested {$requested} items, but there are only {$count} items in the collection."
@@ -1089,10 +1093,6 @@ public function random($amount = null)
10891093
return Arr::random($this->items);
10901094
}
10911095

1092-
if ($amount === 0) {
1093-
return new static;
1094-
}
1095-
10961096
return new static(Arr::random($this->items, $amount));
10971097
}
10981098

tests/Support/SupportCollectionTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,15 @@ public function testRandom()
924924
$this->assertCount(3, $random);
925925
}
926926

927+
public function testRandomOnEmptyCollection()
928+
{
929+
$data = new Collection();
930+
931+
$random = $data->random(0);
932+
$this->assertInstanceOf(Collection::class, $random);
933+
$this->assertCount(0, $random);
934+
}
935+
927936
public function testRandomWithoutArgument()
928937
{
929938
$data = new Collection([1, 2, 3, 4, 5, 6]);

0 commit comments

Comments
 (0)