Skip to content

Commit 040fef6

Browse files
committed
refactor: use an index normalization function instead of array_at()
This fixes a possible (untested) edge case where the $result could have been null even if the index was valid, and also simplifies a possible feature extension to return paths instead of node values.
1 parent dbd6db2 commit 040fef6

2 files changed

Lines changed: 17 additions & 7 deletions

File tree

src/parsers/root.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,12 @@ function apply_index_selector($node, $json)
113113
{
114114
if (is_json_array($json)) {
115115
if ($node->index < sizeof($json)) {
116-
$result = array_at($json, $node->index);
117-
return $result === null ? [] : [$result];
116+
$index = normalize_index($node->index, sizeof($json));
117+
if ($index === null) {
118+
return [];
119+
} else {
120+
return [$json[$index]];
121+
}
118122
}
119123
return [];
120124
}

src/utils/helpers.php

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,14 +84,20 @@ function is_number($value): bool
8484
}
8585

8686
/**
87-
* Get the value at a given index of an array or null if it does not exist
88-
* Allow to use negative indexes
87+
* Normalize an index for a given array length to be positive
88+
* or null if it is out of bounds
89+
* An index is out of bounds if it is less than the negative length
90+
* or greater than or equal to the length
8991
*/
90-
function array_at(array $array, int $index)
92+
function normalize_index($index, int $length): ?int
9193
{
94+
if ($index < -$length || $index >= $length) {
95+
return null;
96+
}
97+
9298
if ($index < 0) {
93-
$index += sizeof($array);
99+
$index += $length;
94100
}
95101

96-
return $array[$index] ?? null;
102+
return $index;
97103
}

0 commit comments

Comments
 (0)