LinksArray::addLinkObject()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
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
 */
13
class LinksArray implements ObjectInterface {
14
	/** @var array with string|LinkObject */
15
	protected $links = [];
16
	
17
	/**
18
	 * human api
19
	 */
20
	
21
	/**
22
	 * @param  string[] $hrefs
23
	 * @return LinksArray
24
	 */
25 4
	public static function fromArray(array $hrefs) {
26 4
		$linksArray = new self();
27
		
28 4
		foreach ($hrefs as $href) {
29 4
			$linksArray->add($href);
30
		}
31
		
32 4
		return $linksArray;
33
	}
34
	
35
	/**
36
	 * @param  object $hrefs
37
	 * @return LinksArray
38
	 */
39 1
	public static function fromObject($hrefs) {
40 1
		$array = Converter::objectToArray($hrefs);
41
		
42 1
		return self::fromArray($array);
43
	}
44
	
45
	/**
46
	 * @param string $href
47
	 * @param array  $meta optional, if given a LinkObject is added, otherwise a link string is added
48
	 */
49 10
	public function add($href, array $meta=[]) {
50 10
		if ($meta === []) {
51 9
			$this->addLinkString($href);
52
		}
53
		else {
54 2
			$this->addLinkObject(new LinkObject($href, $meta));
55
		}
56
	}
57
	
58
	/**
59
	 * spec api
60
	 */
61
	
62
	/**
63
	 * @param string $href
64
	 */
65 9
	public function addLinkString($href) {
66 9
		$this->links[] = $href;
67
	}
68
	
69
	/**
70
	 * @param LinkObject $linkObject
71
	 */
72 4
	public function addLinkObject(LinkObject $linkObject) {
73 4
		$this->links[] = $linkObject;
74
	}
75
	
76
	/**
77
	 * ObjectInterface
78
	 */
79
	
80
	/**
81
	 * @inheritDoc
82
	 */
83 9
	public function isEmpty() {
84 9
		return ($this->links === []);
85
	}
86
	
87
	/**
88
	 * @inheritDoc
89
	 */
90 10
	public function toArray() {
91 10
		$array = [];
92
		
93 10
		foreach ($this->links as $link) {
94 10
			if ($link instanceof LinkObject && $link->isEmpty() === false) {
95 4
				$array[] = $link->toArray();
96
			}
97 8
			elseif (is_string($link)) {
98 8
				$array[] = $link;
99
			}
100
		}
101
		
102 10
		return $array;
103
	}
104
}
105