Created
August 15, 2013 12:27
-
-
Save Thinkscape/6240436 to your computer and use it in GitHub Desktop.
Guzzle path-enabled json response visitor.
This file contains 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
<?php | |
namespace Guzzle\Service\Command\LocationVisitor\Response; | |
use Guzzle\Http\Message\Response; | |
use Guzzle\Service\Command\CommandInterface; | |
use Guzzle\Service\Description\Parameter; | |
class JsonPathVisitor extends JsonVisitor | |
{ | |
public function visit( | |
CommandInterface $command, | |
Response $response, | |
Parameter $param, | |
&$value, | |
$context = null | |
){ | |
$name = $param->getName(); | |
$path = $param->getWireName(); | |
if (!strstr($path, '/')) { | |
return parent::visit($command, $response, $param, $value, $context); | |
} elseif ($param->getData('jsonFlattened')) { | |
if (is_array($value)) { | |
$this->recursiveProcess($param, $value); | |
$value = array( | |
$name => $value | |
); | |
} | |
} elseif (self::issetPath($value, $path)) { | |
$this->recursiveProcess($param, self::getValueAtPath($value, $path)); | |
$value[$name] = self::getValueAtPath($value, $path); | |
self::unsetPath($value, $path); | |
} | |
} | |
protected static function issetPath(&$array, $path) | |
{ | |
$path = explode('/', $path); | |
$pointer = & $array; | |
foreach ($path as $segment) { | |
if (!isset($pointer[$segment])) { | |
return false; | |
} | |
$pointer = & $pointer[$segment]; | |
} | |
return true; | |
} | |
protected static function & getValueAtPath(&$array, $path) | |
{ | |
$path = explode('/', $path); | |
$pointer = & $array; | |
foreach ($path as $segment) { | |
$pointer = & $pointer[$segment]; | |
} | |
return $pointer; | |
} | |
protected static function unsetPath(&$array, $path) | |
{ | |
$path = explode('/', $path); | |
$pointer = & $array; | |
// First, remove the desired value at the top | |
$count = count($path); | |
for ($x = 0; $x < $count - 1; $x++) { | |
if (!isset($pointer[$path[$x]])) { | |
return; // path not found | |
} | |
$pointer = & $pointer[$path[$x]]; | |
} | |
unset($pointer[$path[$x]]); | |
// Now walk downwards from the path and remove any redundant empty elements | |
for ($x = $count - 2; $x >= 0; $x--) { | |
$pointer = & $array; | |
for ($y = 0; $y <= $x - 1; $y++) { | |
$pointer = & $pointer[$path[$y]]; | |
} | |
// remove the element if it's empty | |
if (empty($pointer[$path[$y]])) { | |
unset($pointer[$path[$y]]); | |
} else { | |
break; // nothing more to remove as parent elements contain this one | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment