Skip to content

Commit 5d4ac50

Browse files
markrogoyskiSmoren
authored andcommitted
Fix index criteria to now allow floats. Add tests.
1 parent 666460d commit 5d4ac50

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/Views/ArrayView.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,13 @@ protected function convertIndex(int $i): int
525525
*/
526526
private function numericOffsetExists($offset): bool
527527
{
528-
if (!\is_string($offset) && \is_numeric($offset) && (\is_nan($offset) || \is_infinite($offset))) {
528+
// Non-string must be integer
529+
if (!\is_string($offset) && !\is_int($offset)) {
530+
return false;
531+
}
532+
533+
// Numeric string must be 'integer'
534+
if (\is_string($offset) && \preg_match('/^-?\d+$/', $offset) !== 1) {
529535
return false;
530536
}
531537

tests/unit/ArrayView/IndexTest.php

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ public static function dataProviderForIndexesSmallerThanThanNegativeThree(): arr
287287
* @param mixed $i
288288
* @return void
289289
*/
290-
public function testNonIntegerIndexError($i): void
290+
public function testNonIntegerKeyError($i): void
291291
{
292292
// Given
293293
$array = [10, 20, 30];
@@ -312,4 +312,37 @@ public static function dataProviderForNonIntegerIndexes(): array
312312
['six'],
313313
];
314314
}
315+
316+
/**
317+
* @dataProvider dataProviderForFloatIndexes
318+
* @param mixed $i
319+
* @return void
320+
*/
321+
public function testNonIntegerIndexError($i): void
322+
{
323+
// Given
324+
$array = [10, 20, 30];
325+
$arrayView = ArrayView::toView($array);
326+
327+
// Then
328+
$this->expectException(IndexError::class);
329+
330+
// When
331+
$number = $arrayView[$i];
332+
}
333+
334+
public static function dataProviderForFloatIndexes(): array
335+
{
336+
return [
337+
[0.1],
338+
['0.5'],
339+
['1.5'],
340+
[2.0],
341+
[3.1],
342+
['45.66'],
343+
[\NAN],
344+
[\INF],
345+
[-\INF],
346+
];
347+
}
315348
}

0 commit comments

Comments
 (0)