Skip to content

Commit

Permalink
Update randomElements to return random number of elements when no c…
Browse files Browse the repository at this point in the history
…ount is provided (#658)
  • Loading branch information
calebdw committed Jun 10, 2023
1 parent 7353165 commit f64484a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
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

0 comments on commit f64484a

Please sign in to comment.