decode(file_get_contents("data.json")); * echo $data->spouse->spouse->name; // echos 'Kris Zyp' * echo $data->oldestChild->name; // echos 'Jennika Zyp' * ``` * * @todo In Highlight.php 10.x, mark this class final with a keyword. * * @since 9.16.0.0 Class has been marked as final * * @final * * @internal */ class JsonRef { /** * Array to hold all data paths in the given JSON data. * * @var array */ private $paths = null; /** * Recurse through the data tree and fill an array of paths that reference * the nodes in the decoded JSON data structure. * * @param mixed $s Decoded JSON data (decoded with json_decode) * @param string $r The current path key (for example: '#children.0'). * * @return void */ private function getPaths(&$s, $r = "#") { $this->paths[$r] = &$s; if (is_array($s) || is_object($s)) { foreach ($s as $k => &$v) { if ($k !== "\$ref") { $this->getPaths($v, $r == "#" ? "#{$k}" : "{$r}.{$k}"); } } } } /** * Recurse through the data tree and resolve all path references. * * @param mixed $s Decoded JSON data (decoded with json_decode) * @param int $limit * @param int $depth * * @return void */ private function resolvePathReferences(&$s, $limit = 20, $depth = 1) { if ($depth >= $limit) { return; } ++$depth; if (is_array($s) || is_object($s)) { foreach ($s as $k => &$v) { if ($k === "\$ref") { $s = $this->paths[$v]; } else { $this->resolvePathReferences($v, $limit, $depth); } } } } /** * Decode JSON data that may contain path based references. * * @deprecated 9.16.0.0 This method will be removed in Highlight.php. Make use of `decodeRef` instead. * * @param string|object $json JSON data string or JSON data object * * @return mixed The decoded JSON data */ public function decode($json) { // Clear the path array. $this->paths = array(); // Decode the given JSON data if necessary. $x = is_string($json) ? json_decode($json) : $json; // Get all data paths. $this->getPaths($x); // Resolve all path references. $this->resolvePathReferences($x); // Return the data. return $x; } /** * Decode JSON data that may contain path based references. * * @param object $json JSON data string or JSON data object * * @return void */ public function decodeRef(&$json) { // Clear the path array. $this->paths = array(); // Get all data paths. $this->getPaths($json); // Resolve all path references. $this->resolvePathReferences($json); } }