1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nocarrier; |
4
|
|
|
|
5
|
|
|
class JsonHalFactory |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Decode a application/hal+json document into a Nocarrier\Hal object. |
9
|
|
|
* |
10
|
|
|
* @param string $text |
11
|
|
|
* @param int $depth |
12
|
|
|
* @static |
13
|
|
|
* @access public |
14
|
|
|
* @return \Nocarrier\Hal |
15
|
|
|
*/ |
16
|
|
|
public static function fromJson(Hal $hal, $text, $depth = 0) |
17
|
|
|
{ |
18
|
|
|
list($uri, $links, $embedded, $data) = self::prepareJsonData($text); |
19
|
|
|
$hal->setUri($uri)->setData($data); |
20
|
|
|
self::addJsonLinkData($hal, $links); |
21
|
|
|
|
22
|
|
|
if ($depth > 0) { |
23
|
|
|
self::setEmbeddedResources($hal, $embedded, $depth); |
24
|
|
|
} |
25
|
|
|
$hal->setShouldStripAttributes(false); |
26
|
|
|
return $hal; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $text |
31
|
|
|
*/ |
32
|
|
|
private static function prepareJsonData($text) |
33
|
|
|
{ |
34
|
|
|
$data = json_decode($text, true); |
35
|
|
|
if (json_last_error() != JSON_ERROR_NONE) { |
36
|
|
|
throw new \RuntimeException('The $text parameter must be valid JSON'); |
37
|
|
|
} |
38
|
|
|
$uri = isset($data['_links']['self']['href']) ? $data['_links']['self']['href'] : ""; |
39
|
|
|
unset ($data['_links']['self']); |
40
|
|
|
|
41
|
|
|
$links = isset($data['_links']) ? $data['_links'] : array(); |
42
|
|
|
unset ($data['_links']); |
43
|
|
|
|
44
|
|
|
$embedded = isset($data['_embedded']) ? $data['_embedded'] : array(); |
45
|
|
|
unset ($data['_embedded']); |
46
|
|
|
|
47
|
|
|
return array($uri, $links, $embedded, $data); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param Hal $hal |
52
|
|
|
* @param array $links |
53
|
|
|
*/ |
54
|
|
|
private static function addJsonLinkData($hal, $links) |
55
|
|
|
{ |
56
|
|
|
foreach ($links as $rel => $links) { |
57
|
|
|
if (!isset($links[0]) or !is_array($links[0])) { |
58
|
|
|
$links = array($links); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
foreach ($links as $link) { |
62
|
|
|
$href = $link['href']; |
63
|
|
|
unset($link['href']); |
64
|
|
|
$hal->addLink($rel, $href, $link); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param Hal $hal |
71
|
|
|
* @param array $embedded |
72
|
|
|
* @param integer $depth |
73
|
|
|
*/ |
74
|
|
|
private static function setEmbeddedResources(Hal $hal, $embedded, $depth) |
75
|
|
|
{ |
76
|
|
|
foreach ($embedded as $rel => $embed) { |
77
|
|
|
$isIndexed = array_values($embed) === $embed; |
78
|
|
|
$className = get_class($hal); |
79
|
|
|
if (!$isIndexed) { |
80
|
|
|
$hal->setResource($rel, self::fromJson(new $className, json_encode($embed), $depth - 1)); |
81
|
|
|
} else { |
82
|
|
|
foreach ($embed as $resource) { |
83
|
|
|
$hal->addResource($rel, self::fromJson(new $className, json_encode($resource), $depth - 1)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|