Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,10 @@ public function put($key, $value)
*/
public function random($amount = null)
{
if ($amount === 0) {
return new static;
}

if (($requested = $amount ?: 1) > ($count = $this->count())) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now that 0 is a supported value, this ?: looks a bit dangerous. With PHP 7 we could just replace it with ??, but here with PHP 5 support, I'd suggest the following:

$requested = is_null($amount) ? 1 : $amount;
$count = $this->count();

if ($requested > $count) {
    throw new InvalidArgumentException(
        "You requested {$requested} items, but there are only {$count} items in the collection."
    );
}

throw new InvalidArgumentException(
"You requested {$requested} items, but there are only {$count} items in the collection."
Expand All @@ -1089,10 +1093,6 @@ public function random($amount = null)
return Arr::random($this->items);
}

if ($amount === 0) {
return new static;
}

return new static(Arr::random($this->items, $amount));
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,15 @@ public function testRandom()
$this->assertCount(3, $random);
}

public function testRandomOnEmptyCollection()
{
$data = new Collection();

$random = $data->random(0);
$this->assertInstanceOf(Collection::class, $random);
$this->assertCount(0, $random);
}

public function testRandomWithoutArgument()
{
$data = new Collection([1, 2, 3, 4, 5, 6]);
Expand Down