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

Update randomElements to return random number of elements when no count is provided #658

Merged
merged 1 commit into from
Jun 10, 2023
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
10 changes: 8 additions & 2 deletions src/Faker/Provider/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ public static function randomAscii()
/**
* Returns randomly ordered subsequence of $count elements from a provided array
*
* @todo update default $count to `null` (BC) for next major version
*
* @param array|class-string|\Traversable $array Array to take elements from. Defaults to a-c
* @param int $count Number of elements to take.
* @param int|null $count Number of elements to take. If `null` then returns random number of elements
* @param bool $allowDuplicates Allow elements to be picked several times. Defaults to false
*
* @throws \InvalidArgumentException
Expand Down Expand Up @@ -211,14 +213,18 @@ public static function randomElements($array = ['a', 'b', 'c'], $count = 1, $all

$numberOfElements = count($elements);

if (!$allowDuplicates && $numberOfElements < $count) {
if (!$allowDuplicates && null !== $count && $numberOfElements < $count) {
throw new \LengthException(sprintf(
'Cannot get %d elements, only %d in array',
$count,
$numberOfElements,
));
}

if (null === $count) {
$count = mt_rand(1, $numberOfElements);
}

$randomElements = [];

$keys = array_keys($elements);
Expand Down
5 changes: 5 additions & 0 deletions test/Faker/Provider/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,11 @@ public function testRandomElementsWorksWithoutArgument(): void
self::assertCount(1, BaseProvider::randomElements(), 'Should work without any input');
}

public function testRandomElementsReturnsRandomCountWhenNull(): void
{
self::assertCount(2, BaseProvider::randomElements(['foo', 'bar', 'baz'], null), 'Should return random count when null');
}

public function testRandomElementsWorksWithEmptyArray(): void
{
$randomElements = BaseProvider::randomElements([], 0);
Expand Down