From 20924c85cc39b3f717479628ce911b8b90888a8c Mon Sep 17 00:00:00 2001 From: Smoren Date: Wed, 13 Mar 2024 02:29:02 +0300 Subject: [PATCH] Coverage 100%! --- src/Util.php | 7 +-- tests/unit/Utils/IsArraySequentialTest.php | 58 ++++++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 tests/unit/Utils/IsArraySequentialTest.php diff --git a/src/Util.php b/src/Util.php index fffce06..dd24b7c 100644 --- a/src/Util.php +++ b/src/Util.php @@ -37,13 +37,14 @@ public static function normalizeIndex(int $index, int $containerLength, bool $th * Check if an array is sequential (indexed from 0 to n-1). * * @param array $source The array to check for sequential indexing. + * @param bool $forceCustomImplementation Flag only for tests. * * @return bool Returns true if the array has sequential indexing, false otherwise. */ - public static function isArraySequential(array $source): bool + public static function isArraySequential(array $source, bool $forceCustomImplementation = false): bool { - if (!function_exists('array_is_list')) { - return array_keys($source) === range(0, count($source) - 1); + if (!function_exists('array_is_list') || $forceCustomImplementation) { + return \count($source) === 0 || array_keys($source) === range(0, count($source) - 1); } return array_is_list($source); } diff --git a/tests/unit/Utils/IsArraySequentialTest.php b/tests/unit/Utils/IsArraySequentialTest.php new file mode 100644 index 0000000..6ff00c2 --- /dev/null +++ b/tests/unit/Utils/IsArraySequentialTest.php @@ -0,0 +1,58 @@ +assertTrue(Util::isArraySequential($source)); + $this->assertTrue(Util::isArraySequential($source, true)); + } + + /** + * @dataProvider dataProviderForIsSequentialFalse + */ + public function testIsSequentialFalse(array $source) + { + $this->assertFalse(Util::isArraySequential($source)); + $this->assertFalse(Util::isArraySequential($source, true)); + } + + public function dataProviderForIsSequentialTrue(): array + { + return [ + [[]], + [['']], + [[null]], + [[1]], + [['1']], + [['test']], + [[1, 2, 3]], + [[0 => 1, 1 => 2, 2 => 3]], + [['0' => 1, 1 => 2, 2 => 3]], + [['0' => 1, '1' => 2, '2' => 3]], + [[10, '20', 30.5]], + ]; + } + + public function dataProviderForIsSequentialFalse(): array + { + return [ + [['a' => 1]], + [[1 => 1]], + [[0 => 1, 1 => 2, 3 => 3]], + [[0 => 1, 1 => 2, 2 => 3, 'test' => 123]], + [[1 => 2, 2 => 3]], + [[1 => 2, 3 => 3, 'a' => 1000]], + ]; + } +}