Skip to content

Commit

Permalink
Merge pull request #54 from Galbar/fix_53_revert_length_functionality
Browse files Browse the repository at this point in the history
Fix #53: revert .length operator functionality to avoid breaking change
  • Loading branch information
Galbar authored Aug 19, 2021
2 parents 39a56a3 + 2d53dc6 commit 38fdd37
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/Galbar/JsonPath/JsonObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public function getJson($options=0)
public function get($jsonPath)
{
list($result, $hasDiverged) = JsonPath::get($this->jsonObject, $jsonPath);
if ($this->smartGet && $result !== false && !$hasDiverged) {
if ($this->smartGet && $result !== false && !$hasDiverged && is_array($result)) {
return $result[0];
}
return $result;
Expand Down Expand Up @@ -251,7 +251,7 @@ public function getJsonObjects($jsonPath)
$jsonObject->jsonObject = &$value;
$objs[] = $jsonObject;
}
if ($this->smartGet && !$hasDiverged) {
if ($this->smartGet && !$hasDiverged && is_array($result)) {
return $objs[0];
}
return $objs;
Expand Down
8 changes: 6 additions & 2 deletions src/Galbar/JsonPath/JsonPath.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,12 @@ public static function subtreeGet(&$root, &$partial, $jsonPath, $createInexisten
$newSelection = array_merge($newSelection, $result);
}
if (empty($newSelection) && Language\Token::LENGTH === $childName) {
foreach ($selection as $item) {
$newSelection[] = is_array($item) ? count($item) : strlen($item);
if (count($selection) > 1) {
foreach ($selection as $item) {
$newSelection[] = is_array($item) ? count($item) : strlen($item);
}
} else if (count($selection) == 1) {
$newSelection = is_array($selection[0]) ? count($selection[0]) : strlen($selection[0]);
}
}
if (empty($newSelection)) {
Expand Down
6 changes: 3 additions & 3 deletions tests/Galbar/JsonPath/JsonObjectLengthOperatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,22 +156,22 @@ public function testLength()
$jsonObject = new JsonObject($this->json);
$result = $jsonObject->get($jsonPath);
$this->assertEquals(
[3],
3,
$result
);

/** String Length Test */
$jsonPath = '$.music.bands[0].albums[0].length.length';
$result = $jsonObject->get($jsonPath);
$this->assertEquals(
[5],
5,
$result
);

$jsonPath = '$.music.bands[0].albums[1].title.length';
$result = $jsonObject->get($jsonPath);
$this->assertEquals(
[6],
6,
$result
);
}
Expand Down

0 comments on commit 38fdd37

Please sign in to comment.