Skip to content

Commit 01da70a

Browse files
oleg-andreyevSoftCreatR
authored andcommitted
fixes #5
added negative check before doing slice
1 parent ed6b57b commit 01da70a

File tree

2 files changed

+64
-18
lines changed

2 files changed

+64
-18
lines changed

src/AccessHelper.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public static function keyExists($collection, $key, $magicIsAllowed = false): bo
6767
}
6868

6969
if (is_object($collection)) {
70-
return property_exists($collection, $key);
70+
return property_exists($collection, (string) $key);
7171
}
7272

7373
return false;
@@ -90,7 +90,7 @@ public static function getValue($collection, $key, $magicIsAllowed = false)
9090
}
9191

9292
if (is_array($collection)) {
93-
if (is_int($key)) {
93+
if (is_int($key) && $key < 0) {
9494
return array_slice($collection, $key, 1, false)[0];
9595
}
9696

tests/JSONPathTest.php

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ public function testChildOperators(): void
3131
self::assertEquals('Sayings of the Century', $result[0]);
3232
}
3333

34+
public function testIndexesObject(): void
35+
{
36+
$result = (new JSONPath($this->exampleIndexedObject(random_int(0, 1))))->find('$.store.books[3].title');
37+
38+
self::assertEquals('Sword of Honour', $result[0]);
39+
}
40+
3441
/**
3542
* $['store']['books'][0]['title']
3643
*
@@ -800,22 +807,61 @@ public function exampleDataWithSlashes(int $asArray = 1)
800807
public function exampleDataWithDots(int $asArray = 1)
801808
{
802809
$json = '
803-
{
804-
"data": {
805-
"tokens": [
806-
{
807-
"Employee.FirstName": "Jack"
808-
},
809-
{
810-
"Employee.LastName": "Daniels"
811-
},
812-
{
813-
"Employee.Email": "[email protected]"
814-
}
815-
]
816-
}
817-
}
818-
';
810+
{
811+
"data": {
812+
"tokens": [
813+
{
814+
"Employee.FirstName": "Jack"
815+
},
816+
{
817+
"Employee.LastName": "Daniels"
818+
},
819+
{
820+
"Employee.Email": "[email protected]"
821+
}
822+
]
823+
}
824+
}
825+
';
826+
827+
return json_decode($json, $asArray === 1);
828+
}
829+
830+
public function exampleIndexedObject(int $asArray = 1)
831+
{
832+
$json = '
833+
{
834+
"store":{
835+
"books":{
836+
"4": {
837+
"category":"reference",
838+
"author":"Nigel Rees",
839+
"title":"Sayings of the Century",
840+
"price":8.95
841+
},
842+
"3": {
843+
"category":"fiction",
844+
"author":"Evelyn Waugh",
845+
"title":"Sword of Honour",
846+
"price":12.99
847+
},
848+
"2": {
849+
"category":"fiction",
850+
"author":"Herman Melville",
851+
"title":"Moby Dick",
852+
"isbn":"0-553-21311-3",
853+
"price":8.99
854+
},
855+
"1": {
856+
"category":"fiction",
857+
"author":"J. R. R. Tolkien",
858+
"title":"The Lord of the Rings",
859+
"isbn":"0-395-19395-8",
860+
"price":22.99
861+
}
862+
}
863+
}
864+
}';
819865

820866
return json_decode($json, $asArray === 1);
821867
}

0 commit comments

Comments
 (0)