Created
May 15, 2012 21:41
-
-
Save mlconnor/2705363 to your computer and use it in GitHub Desktop.
Ognl Like Path Parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$context = json_decode('{"this":{"that":{"some":[0,1,{"in":{"some":{"place":6}}}]}}}'); | |
if ( ! $context ) throw new Exception('json parsing failed'); | |
print OgnlPath::getValue('this.that.some[2].in.some.place', $context ); | |
class OgnlPath { | |
public static function getValue($expression, $context) { | |
$tokens = preg_split('/(\[[^\]]+\])|(?:\.)/', $expression, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); | |
print_r($tokens); | |
//print "context is " . print_r($context, true) . "\n"; | |
foreach ($tokens as $index => $match) { | |
if ( preg_match('|^\[([^\]]+)]$|', $match, $indexMatches) ) { | |
$index = $indexMatches[1]; | |
if ( ! is_array($context) ) throw new Exception('element is not an array for reference ' . $match); | |
if ( $index > count($context) - 1) throw new Exception('array element out of bounds ' . $match); | |
$context = $context[$index]; | |
} else { | |
if ( property_exists($context, $match) ) { | |
$context = $context->$match; | |
} | |
} | |
//print "context is " . print_r($context, true) . "\n"; | |
} | |
return $context; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment