1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace alsvanzelf\jsonapi\objects; |
4
|
|
|
|
5
|
|
|
use alsvanzelf\jsonapi\helpers\Converter; |
6
|
|
|
use alsvanzelf\jsonapi\interfaces\ObjectInterface; |
7
|
|
|
use alsvanzelf\jsonapi\objects\LinkObject; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* an array of links (strings and LinkObjects), used for: |
11
|
|
|
* - type links in an ErrorObject |
12
|
|
|
* - profile links at root level |
13
|
|
|
*/ |
|
|
|
|
14
|
|
|
class LinksArray implements ObjectInterface { |
15
|
|
|
/** @var array with string|LinkObject */ |
16
|
|
|
protected $links = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* human api |
20
|
|
|
*/ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string[] $hrefs |
|
|
|
|
24
|
|
|
* @return LinksArray |
25
|
|
|
*/ |
26
|
|
|
public static function fromArray(array $hrefs) { |
27
|
|
|
$linksArray = new self(); |
28
|
|
|
|
29
|
|
|
foreach ($hrefs as $href) { |
30
|
|
|
$linksArray->add($href); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
return $linksArray; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param object $hrefs |
|
|
|
|
38
|
|
|
* @return LinksArray |
39
|
|
|
*/ |
40
|
|
|
public static function fromObject($hrefs) { |
41
|
|
|
$array = Converter::objectToArray($hrefs); |
42
|
|
|
|
43
|
|
|
return self::fromArray($array); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $href |
|
|
|
|
48
|
|
|
* @param array $meta optional, if given a LinkObject is added, otherwise a link string is added |
49
|
|
|
*/ |
|
|
|
|
50
|
|
|
public function add($href, array $meta=[]) { |
51
|
|
|
if ($meta === []) { |
52
|
|
|
$this->addLinkString($href); |
53
|
|
|
} |
54
|
|
|
else { |
55
|
|
|
$this->addLinkObject(new LinkObject($href, $meta)); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* spec api |
61
|
|
|
*/ |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $href |
|
|
|
|
65
|
|
|
*/ |
|
|
|
|
66
|
|
|
public function addLinkString($href) { |
67
|
|
|
$this->links[] = $href; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param LinkObject $linkObject |
|
|
|
|
72
|
|
|
*/ |
|
|
|
|
73
|
|
|
public function addLinkObject(LinkObject $linkObject) { |
74
|
|
|
$this->links[] = $linkObject; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* ObjectInterface |
79
|
|
|
*/ |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @inheritDoc |
83
|
|
|
*/ |
|
|
|
|
84
|
|
|
public function isEmpty() { |
85
|
|
|
return ($this->links === []); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* @inheritDoc |
90
|
|
|
*/ |
|
|
|
|
91
|
|
|
public function toArray() { |
92
|
|
|
$array = []; |
93
|
|
|
|
94
|
|
|
foreach ($this->links as $link) { |
95
|
|
|
if ($link instanceof LinkObject && $link->isEmpty() === false) { |
96
|
|
|
$array[] = $link->toArray(); |
97
|
|
|
} |
98
|
|
|
elseif (is_string($link)) { |
99
|
|
|
$array[] = $link; |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
return $array; |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|