Skip to content

Commit

Permalink
Fix index criteria to now allow floats. Add tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
markrogoyski authored and Smoren committed Mar 14, 2024
1 parent 666460d commit 5d4ac50
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/Views/ArrayView.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
35 changes: 34 additions & 1 deletion tests/unit/ArrayView/IndexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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],
];
}
}

0 comments on commit 5d4ac50

Please sign in to comment.