Skip to content

Commit

Permalink
A::random(): exception if $count exceeds array
Browse files Browse the repository at this point in the history
Fixes #5934
  • Loading branch information
distantnative committed Jul 22, 2024
1 parent 880f30e commit 137628b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Toolkit/A.php
Original file line number Diff line number Diff line change
Expand Up @@ -738,12 +738,18 @@ public static function nestByKeys($value, array $keys)
/**
* Returns a number of random elements from an array,
* either in original or shuffled order
*
* @throws \Exception When $count is larger than array length
*/
public static function random(
array $array,
int $count = 1,
bool $shuffle = false
): array {
if ($count > count($array)) {
throw new Exception('$count is larger than available array items');
}

if ($shuffle === true) {
return array_slice(self::shuffle($array), 0, $count);
}
Expand Down
10 changes: 10 additions & 0 deletions tests/Toolkit/ATest.php
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,16 @@ public function testRandom()
}
}

/**
* @covers ::random
*/
public function testRandomInvalidCount()
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('$count is larger than available array items');
A::random([1,2,3], 4);
}

/**
* @covers ::fill
*/
Expand Down

0 comments on commit 137628b

Please sign in to comment.