Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] allow Collection random() to accept a callable #43028

Merged
merged 1 commit into from
Jul 1, 2022
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
6 changes: 5 additions & 1 deletion src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,7 @@ public function put($key, $value)
/**
* Get one or a specified number of items randomly from the collection.
*
* @param int|null $number
* @param (callable(TValue): int)|int|null $number
* @return static<int, TValue>|TValue
*
* @throws \InvalidArgumentException
Expand All @@ -989,6 +989,10 @@ public function random($number = null)
return Arr::random($this->items);
}

if (is_callable($number)) {
return new static(Arr::random($this->items, $number($this)));
}

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

Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2285,6 +2285,10 @@ public function testRandom($collection)
$random = $data->random('2');
$this->assertInstanceOf($collection, $random);
$this->assertCount(2, $random);

$random = $data->random(fn($items) => min(10, count($items)));
$this->assertInstanceOf($collection, $random);
$this->assertCount(6, $random);
}

/**
Expand Down