From f64484a5d699d9f7c7e1a483b260340187a96a33 Mon Sep 17 00:00:00 2001 From: CalebW Date: Sat, 10 Jun 2023 06:43:19 -0500 Subject: [PATCH] Update `randomElements` to return random number of elements when no count is provided (#658) --- src/Faker/Provider/Base.php | 10 ++++++++-- test/Faker/Provider/BaseTest.php | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Faker/Provider/Base.php b/src/Faker/Provider/Base.php index 675cf89e76..d91552c8a3 100644 --- a/src/Faker/Provider/Base.php +++ b/src/Faker/Provider/Base.php @@ -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 @@ -211,7 +213,7 @@ 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, @@ -219,6 +221,10 @@ public static function randomElements($array = ['a', 'b', 'c'], $count = 1, $all )); } + if (null === $count) { + $count = mt_rand(1, $numberOfElements); + } + $randomElements = []; $keys = array_keys($elements); diff --git a/test/Faker/Provider/BaseTest.php b/test/Faker/Provider/BaseTest.php index bb64857f8a..78d3b24042 100644 --- a/test/Faker/Provider/BaseTest.php +++ b/test/Faker/Provider/BaseTest.php @@ -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);