Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update JsonStore #3

Merged
merged 2 commits into from
May 18, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions src/Peekmo/JsonPath/JsonStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,30 @@
* Modified by Axel Anceau
*/

class JsonStore
class JsonStore
{
function toString($obj)
private static $emptyArray = array();

function toString($obj)
{
return json_encode($obj);
}

function asObj($jsonstr)
function asObj($jsonstr)
{
return json_decode($jsonstr);
}

function& get(&$obj, $expr)
function& get(&$obj, $expr)
{
if (($exprs = JsonStore::_normalizedFirst($obj, $expr)) !== false) {
if ((($exprs = JsonStore::_normalizedFirst($obj, $expr)) !== false) &&
(is_array($exprs) || $exprs instanceof Traversable)) {
$values = array();

foreach ($exprs as $expr) {
$o =& $obj;
$keys = preg_split("/([\"'])?\]\[([\"'])?/", preg_replace(array("/^\\$\[[\"']?/", "/[\"']?\]$/"), "", $expr));

for ($i=0; $i<count($keys); $i++) {
$o =& $o[$keys[$i]];
}
Expand All @@ -40,21 +44,25 @@ function& get(&$obj, $expr)
return $values;
}

return null;
return self::$emptyArray;
}

function set(&$obj, $expr, $value)
function set(&$obj, $expr, $value)
{
if ($res =& JsonStore::get($obj, $expr)) {
foreach ($res as &$r) {
$r = $value;
}

return true;
}

return false;
}

function add(&$obj, $parentexpr, $value, $name="")
function add(&$obj, $parentexpr, $value, $name="")
{
$parents =& JsonStore::get($obj, $parentexpr);
if($parents =& JsonStore::get($obj, $parentexpr)) {
foreach ($parents as &$parent) {
$parent = is_array($parent) ? $parent : array();

Expand All @@ -64,11 +72,17 @@ function add(&$obj, $parentexpr, $value, $name="")
$parent[] = $value;
}
}

return true;
}

return false;
}

function remove(&$obj, $expr)
function remove(&$obj, $expr)
{
if (($exprs = JsonStore::_normalizedFirst($obj, $expr)) !== false) {
if ((($exprs = JsonStore::_normalizedFirst($obj, $expr)) !== false) &&
(is_array($exprs) || $exprs instanceof Traversable)) {
foreach ($exprs as &$expr) {
$o =& $obj;
$keys = preg_split("/([\"'])?\]\[([\"'])?/", preg_replace(array("/^\\$\[[\"']?/", "/[\"']?\]$/"), "", $expr));
Expand All @@ -85,7 +99,7 @@ function remove(&$obj, $expr)
return false;
}

function _normalizedFirst($o, $expr)
function _normalizedFirst($o, $expr)
{
if ($expr == "") {
return false;
Expand All @@ -99,4 +113,4 @@ function _normalizedFirst($o, $expr)
}
}
}
?>
?>