Skip to content

Commit f64484a

Browse files
authored
Update randomElements to return random number of elements when no count is provided (#658)
1 parent 7353165 commit f64484a

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/Faker/Provider/Base.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,10 @@ public static function randomAscii()
179179
/**
180180
* Returns randomly ordered subsequence of $count elements from a provided array
181181
*
182+
* @todo update default $count to `null` (BC) for next major version
183+
*
182184
* @param array|class-string|\Traversable $array Array to take elements from. Defaults to a-c
183-
* @param int $count Number of elements to take.
185+
* @param int|null $count Number of elements to take. If `null` then returns random number of elements
184186
* @param bool $allowDuplicates Allow elements to be picked several times. Defaults to false
185187
*
186188
* @throws \InvalidArgumentException
@@ -211,14 +213,18 @@ public static function randomElements($array = ['a', 'b', 'c'], $count = 1, $all
211213

212214
$numberOfElements = count($elements);
213215

214-
if (!$allowDuplicates && $numberOfElements < $count) {
216+
if (!$allowDuplicates && null !== $count && $numberOfElements < $count) {
215217
throw new \LengthException(sprintf(
216218
'Cannot get %d elements, only %d in array',
217219
$count,
218220
$numberOfElements,
219221
));
220222
}
221223

224+
if (null === $count) {
225+
$count = mt_rand(1, $numberOfElements);
226+
}
227+
222228
$randomElements = [];
223229

224230
$keys = array_keys($elements);

test/Faker/Provider/BaseTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,11 @@ public function testRandomElementsWorksWithoutArgument(): void
580580
self::assertCount(1, BaseProvider::randomElements(), 'Should work without any input');
581581
}
582582

583+
public function testRandomElementsReturnsRandomCountWhenNull(): void
584+
{
585+
self::assertCount(2, BaseProvider::randomElements(['foo', 'bar', 'baz'], null), 'Should return random count when null');
586+
}
587+
583588
public function testRandomElementsWorksWithEmptyArray(): void
584589
{
585590
$randomElements = BaseProvider::randomElements([], 0);

0 commit comments

Comments
 (0)