1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nocarrier; |
4
|
|
|
|
5
|
|
|
class XmlHalFactory |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Decode a application/hal+xml document into a Nocarrier\Hal object. |
9
|
|
|
* |
10
|
|
|
* @param Hal $hal |
11
|
|
|
* @param $data |
12
|
|
|
* @param int $depth |
13
|
|
|
* |
14
|
|
|
* @throws \RuntimeException |
15
|
|
|
* @static |
16
|
|
|
* @access public |
17
|
|
|
* @return \Nocarrier\Hal |
18
|
|
|
*/ |
19
|
|
|
public static function fromXml(Hal $hal, $data, $depth = 0) |
20
|
|
|
{ |
21
|
|
|
if (!$data instanceof \SimpleXMLElement) { |
22
|
|
|
try { |
23
|
|
|
$data = new \SimpleXMLElement($data); |
24
|
|
|
} catch (\Exception $e) { |
25
|
|
|
throw new \RuntimeException('The $data parameter must be valid XML'); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$children = $data->children(); |
30
|
|
|
$links = clone $children->link; |
31
|
|
|
unset ($children->link); |
32
|
|
|
|
33
|
|
|
$embedded = clone $children->resource; |
34
|
|
|
unset ($children->resource); |
35
|
|
|
|
36
|
|
|
$hal->setUri((string)$data->attributes()->href); |
37
|
|
|
$hal->setData((array) $children); |
38
|
|
|
foreach ($links as $links) { |
39
|
|
|
if (!is_array($links)) { |
40
|
|
|
$links = array($links); |
41
|
|
|
} |
42
|
|
|
foreach ($links as $link) { |
43
|
|
|
list($rel, $href, $attributes) = self::extractKnownData($link); |
44
|
|
|
$hal->addLink($rel, $href, $attributes); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if ($depth > 0) { |
49
|
|
|
foreach ($embedded as $embed) { |
50
|
|
|
list($rel, $href, $attributes) = self::extractKnownData($embed); |
|
|
|
|
51
|
|
|
$hal->addResource($rel, self::fromXml($embed, $depth - 1)); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
$hal->setShouldStripAttributes(false); |
55
|
|
|
return $hal; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private static function extractKnownData($data) |
59
|
|
|
{ |
60
|
|
|
$attributes = (array)$data->attributes(); |
61
|
|
|
$attributes = $attributes['@attributes']; |
62
|
|
|
$rel = $attributes['rel']; |
63
|
|
|
$href = $attributes['href']; |
64
|
|
|
unset($attributes['rel'], $attributes['href']); |
65
|
|
|
|
66
|
|
|
return array($rel, $href, $attributes); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
This checks looks for assignemnts to variables using the
list(...)
function, where not all assigned variables are subsequently used.Consider the following code example.
Only the variables
$a
and$c
are used. There was no need to assign$b
.Instead, the list call could have been.