/** * Decode a application/hal+xml document into a Nocarrier\Hal object. * * @param Hal $hal * @param $data * @param int $depth * * @throws \RuntimeException * @static * @access public * @return \Nocarrier\Hal */ public static function fromXml(Hal $hal, $data, $depth = 0) { if (!$data instanceof \SimpleXMLElement) { try { $data = new \SimpleXMLElement($data); } catch (\Exception $e) { throw new \RuntimeException('The $data parameter must be valid XML'); } } $children = $data->children(); $links = clone $children->link; unset($children->link); $embedded = clone $children->resource; unset($children->resource); $hal->setUri((string) $data->attributes()->href); $hal->setData((array) $children); foreach ($links as $links) { if (!is_array($links)) { $links = array($links); } foreach ($links as $link) { list($rel, $href, $attributes) = self::extractKnownData($link); $hal->addLink($rel, $href, $attributes); } } if ($depth > 0) { foreach ($embedded as $embed) { list($rel, $href, $attributes) = self::extractKnownData($embed); $hal->addResource($rel, self::fromXml($embed, $depth - 1)); } } $hal->setShouldStripAttributes(false); return $hal; }
/** * Decode a application/hal+json document into a Nocarrier\Hal object. * * @param string $text * @param int $max_depth * @static * @access public * @return \Nocarrier\Hal */ public static function fromJson($text, $max_depth = 0) { $data = json_decode($text, true); $uri = $data['_links']['self']['href']; unset($data['_links']['self']); $links = $data['_links']; unset($data['_links']); $embedded = isset($data['_embedded']) ? $data['_embedded'] : array(); unset($data['_embedded']); $hal = new Hal($uri, $data); foreach ($links as $rel => $links) { if (!isset($links[0]) or !is_array($links[0])) { $links = array($links); } foreach ($links as $link) { $href = $link['href']; unset($link['href'], $link['title']); $hal->addLink($rel, $href, $link); } } if ($max_depth > 0) { foreach ($embedded as $rel => $embed) { if (!is_array($embed)) { $hal->addResource($rel, self::fromJson(json_encode($embed), $max_depth - 1)); } else { foreach ($embed as $child_resource) { $hal->addResource($rel, self::fromJson(json_encode($child_resource), $max_depth - 1)); } } } } return $hal; }