diff --git a/src/Toolkit/A.php b/src/Toolkit/A.php index b30b83675f..1970cc9861 100644 --- a/src/Toolkit/A.php +++ b/src/Toolkit/A.php @@ -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 InvalidArgumentException('$count is larger than available array items'); + } + if ($shuffle === true) { return array_slice(self::shuffle($array), 0, $count); } diff --git a/tests/Toolkit/ATest.php b/tests/Toolkit/ATest.php index 8ea33567cf..489aa46826 100644 --- a/tests/Toolkit/ATest.php +++ b/tests/Toolkit/ATest.php @@ -697,6 +697,16 @@ public function testRandom() } } + /** + * @covers ::random + */ + public function testRandomInvalidCount() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('$count is larger than available array items'); + A::random([1, 2, 3], 4); + } + /** * @covers ::fill */