diff --git a/src/Views/ArrayView.php b/src/Views/ArrayView.php index b5acdc4..0cac457 100644 --- a/src/Views/ArrayView.php +++ b/src/Views/ArrayView.php @@ -525,7 +525,13 @@ protected function convertIndex(int $i): int */ private function numericOffsetExists($offset): bool { - if (!\is_string($offset) && \is_numeric($offset) && (\is_nan($offset) || \is_infinite($offset))) { + // Non-string must be integer + if (!\is_string($offset) && !\is_int($offset)) { + return false; + } + + // Numeric string must be 'integer' + if (\is_string($offset) && \preg_match('/^-?\d+$/', $offset) !== 1) { return false; } diff --git a/tests/unit/ArrayView/IndexTest.php b/tests/unit/ArrayView/IndexTest.php index 410873a..6f77c08 100644 --- a/tests/unit/ArrayView/IndexTest.php +++ b/tests/unit/ArrayView/IndexTest.php @@ -287,7 +287,7 @@ public static function dataProviderForIndexesSmallerThanThanNegativeThree(): arr * @param mixed $i * @return void */ - public function testNonIntegerIndexError($i): void + public function testNonIntegerKeyError($i): void { // Given $array = [10, 20, 30]; @@ -312,4 +312,37 @@ public static function dataProviderForNonIntegerIndexes(): array ['six'], ]; } + + /** + * @dataProvider dataProviderForFloatIndexes + * @param mixed $i + * @return void + */ + public function testNonIntegerIndexError($i): void + { + // Given + $array = [10, 20, 30]; + $arrayView = ArrayView::toView($array); + + // Then + $this->expectException(IndexError::class); + + // When + $number = $arrayView[$i]; + } + + public static function dataProviderForFloatIndexes(): array + { + return [ + [0.1], + ['0.5'], + ['1.5'], + [2.0], + [3.1], + ['45.66'], + [\NAN], + [\INF], + [-\INF], + ]; + } }