Passed
Push — master ( c1150e...84b7ab )
by Michael
02:30
created

LinksContainer::getLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Document\Behaviour;
5
6
use Mikemirten\Component\JsonApi\Document\LinkObject;
7
8
/**
9
 * Links-container behaviour
10
 *
11
 * @see http://jsonapi.org/format/#document-links
12
 *
13
 * @package Mikemirten\Component\JsonApi\Document\Behaviour
14
 */
15
trait LinksContainer
16
{
17
    /**
18
     * Links
19
     *
20
     * @var LinkObject[]
21
     */
22
    protected $links = [];
23
24
    /**
25
     * Set link
26
     *
27
     * @param string     $name
28
     * @param LinkObject $link
29
     */
30
    public function setLink(string $name, LinkObject $link)
31
    {
32
        $this->links[$name] = $link;
33
    }
34
35
    /**
36
     * Has link
37
     *
38
     * @param  string $name
39
     * @return bool
40
     */
41
    public function hasLink(string $name): bool
42
    {
43
        return isset($this->links[$name]);
44
    }
45
46
    /**
47
     * Get link
48
     *
49
     * @param  string $name
50
     * @return LinkObject
51
     */
52
    public function getLink(string $name): LinkObject
53
    {
54
        return $this->links[$name];
55
    }
56
57
    /**
58
     * Get all links
59
     *
60
     * @return LinkObject[]
61
     */
62
    public function getLinks(): array
63
    {
64
        return $this->links;
65
    }
66
67
    /**
68
     * Contains any links ?
69
     *
70
     * @return bool
71
     */
72
    public function hasLinks(): bool
73
    {
74
        return count($this->links) > 0;
75
    }
76
77
    /**
78
     * Cast links to an array
79
     *
80
     * @return array
81
     */
82
    protected function linksToArray(): array
83
    {
84
        $links = [];
85
86
        foreach ($this->links as $name => $link)
87
        {
88
            if (! $link->hasMetadata()) {
89
                $links[$name] = $link->getReference();
90
                continue;
91
            }
92
93
            $links[$name] = [
94
                'href' => $link->getReference(),
95
                'meta' => $link->getMetadata()
96
            ];
97
        }
98
99
        return $links;
100
    }
101
}