From 7891c3d013521801f3144e5f0316f13e62bfc2c9 Mon Sep 17 00:00:00 2001 From: cwhite Date: Fri, 9 Jun 2023 09:18:05 -0500 Subject: [PATCH] Update `randomElements` to return random number of elements when no count is provided --- 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);