From 115a6dc28311fb205ef9953a875cca29ff1bdfcf Mon Sep 17 00:00:00 2001 From: Nico Hoffmann Date: Mon, 22 Jul 2024 13:23:07 +0200 Subject: [PATCH 1/2] `A::random()`: exception if $count exceeds array Fixes #5934 --- src/Toolkit/A.php | 6 ++++++ tests/Toolkit/ATest.php | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/Toolkit/A.php b/src/Toolkit/A.php index b30b83675f..e23906e800 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 Exception('$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..8f22bfb789 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(Exception::class); + $this->expectExceptionMessage('$count is larger than available array items'); + A::random([1, 2, 3], 4); + } + /** * @covers ::fill */ From 960b050b8239544e5d24caeff63e2bc1dcb2dfb8 Mon Sep 17 00:00:00 2001 From: Nico Hoffmann Date: Mon, 22 Jul 2024 16:58:10 +0200 Subject: [PATCH 2/2] Change exception type --- src/Toolkit/A.php | 2 +- tests/Toolkit/ATest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Toolkit/A.php b/src/Toolkit/A.php index e23906e800..1970cc9861 100644 --- a/src/Toolkit/A.php +++ b/src/Toolkit/A.php @@ -747,7 +747,7 @@ public static function random( bool $shuffle = false ): array { if ($count > count($array)) { - throw new Exception('$count is larger than available array items'); + throw new InvalidArgumentException('$count is larger than available array items'); } if ($shuffle === true) { diff --git a/tests/Toolkit/ATest.php b/tests/Toolkit/ATest.php index 8f22bfb789..489aa46826 100644 --- a/tests/Toolkit/ATest.php +++ b/tests/Toolkit/ATest.php @@ -702,7 +702,7 @@ public function testRandom() */ public function testRandomInvalidCount() { - $this->expectException(Exception::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('$count is larger than available array items'); A::random([1, 2, 3], 4); }