Completed
Push — hal-link ( 2c1f46 )
by Akihito
02:27
created

HalLink::linkAnnotation()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 4
nc 4
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Annotation\Link;
8
use Nocarrier\Hal;
9
10
final class HalLink
11
{
12
    /**
13
     * @var ReverseLinkInterface
14
     */
15
    private $link;
16
17
    public function __construct(ReverseLinkInterface $link)
18
    {
19
        $this->link = $link;
20
    }
21
22
    public function getReverseLink(string $uri) : string
23
    {
24
        return ($this->link)($uri);
25
    }
26
27
    public function addHalLink(array $body, array $methodAnnotations, Hal $hal) : Hal
28
    {
29
        if (! empty($methodAnnotations)) {
30
            $hal = $this->linkAnnotation($body, $methodAnnotations, $hal);
31
        }
32
        if (isset($body['_links'])) {
33
            $hal = $this->bodyLink($body, $hal);
34
        }
35
36
        return $hal;
37
    }
38
39
    private function linkAnnotation(array $body, array $methodAnnotations, Hal $hal) : Hal
40
    {
41
        foreach ($methodAnnotations as $annotation) {
42
            if (! $annotation instanceof Link) {
43
                continue;
44
            }
45
            $uri = uri_template($annotation->href, $body);
46
            $reverseUri = $this->getReverseLink($uri);
47
            if (isset($body['_links'][$annotation->rel])) {
48
                // skip if already difined links in ResourceObject
49
                continue;
50
            }
51
            $hal->addLink($annotation->rel, $reverseUri);
52
        }
53
54
        return $hal;
55
    }
56
57
    private function bodyLink(array $body, Hal $hal) : Hal
58
    {
59
        foreach ((array) $body['_links'] as $rel => $link) {
60
            $attr = $link;
61
            unset($attr['href']);
62
            $hal->addLink($rel, $link['href'], $attr);
63
        }
64
65
        return $hal;
66
    }
67
}
68