Peekmo\JsonPath\JsonStore::get PHP Method

get() public method

Gets elements matching the given JsonPath expression
public get ( string $expr, boolean $unique = false ) : array
$expr string JsonPath expression
$unique boolean Gets unique results or not
return array
    public function get($expr, $unique = false)
    {
        if (($exprs = $this->normalizedFirst($expr)) !== false && (is_array($exprs) || $exprs instanceof \Traversable)) {
            $values = array();
            foreach ($exprs as $expr) {
                $o =& $this->data;
                $keys = preg_split("/([\"'])?\\]\\[([\"'])?/", preg_replace(array("/^\\\$\\[[\"']?/", "/[\"']?\\]\$/"), "", $expr));
                for ($i = 0; $i < count($keys); $i++) {
                    $o =& $o[$keys[$i]];
                }
                $values[] =& $o;
            }
            if (true === $unique) {
                if (!empty($values) && is_array($values[0])) {
                    array_walk($values, function (&$value) {
                        $value = json_encode($value);
                    });
                    $values = array_unique($values);
                    array_walk($values, function (&$value) {
                        $value = json_decode($value, true);
                    });
                    return array_values($values);
                }
                return array_unique($values);
            }
            return $values;
        }
        return self::$emptyArray;
    }

Usage Example

Beispiel #1
0
 public function doValidation(Response $response)
 {
     $body = (string) $response->getBody();
     $json = json_decode($body);
     if (!$json) {
         throw new ValidationFailedException('The given json document is empty or not valid json.');
     }
     $store = new JsonStore($json);
     $error = false;
     $noCorrectJsonPaths = array();
     foreach ($this->jsonPaths as $path) {
         $jsonValue = $store->get($path['pattern']);
         $count = count($jsonValue);
         if ($jsonValue === FALSE || is_array($jsonValue) && empty($jsonValue)) {
             $error = true;
             $noCorrectJsonPaths[] = $path['pattern'] . ' (JSON Path not found)';
         }
         if ($this->checkRelation($path['relation'], $path['value'], $count) === false) {
             $error = true;
             $noCorrectJsonPaths[] = $path['pattern'] . ' (number of JSONPaths is not correct corresponding to the given relation/value)';
         }
     }
     if ($error === true) {
         $allNoCorrectJsonPaths = implode('", "', $noCorrectJsonPaths);
         throw new ValidationFailedException('Disonances with JSON Paths "' . $allNoCorrectJsonPaths . '!');
     }
 }
All Usage Examples Of Peekmo\JsonPath\JsonStore::get