Completed
Push — 1.x ( abde83...7c6f23 )
by Akihito
13s
created

HalLink::addHalLink()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 3
crap 3
1
<?php
2
/**
3
 * This file is part of the BEAR.Package package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\Package\Provide\Representation;
8
9
use BEAR\Resource\Annotation\Link;
10
use BEAR\Sunday\Extension\Router\RouterInterface;
11
use Nocarrier\Hal;
12
13
final class HalLink
14
{
15
    /**
16
     * @var RouterInterface
17
     */
18
    private $router;
19
20 14
    public function __construct(RouterInterface $router)
21
    {
22 14
        $this->router = $router;
23 14
    }
24
25 11
    public function getReverseLink($uri) : string
26
    {
27 11
        $urlParts = parse_url($uri);
28 11
        $routeName = $urlParts['path'];
29 11
        isset($urlParts['query']) ? parse_str($urlParts['query'], $value) : $value = [];
30 11
        if ($value === []) {
31 5
            return $uri;
32
        }
33 8
        $reverseUri = $this->router->generate($routeName, (array) $value);
34 8
        if (is_string($reverseUri)) {
35 2
            return $reverseUri;
36
        }
37
38 6
        return $uri;
39
    }
40
41 11
    public function addHalLink(array $body, array $methodAnnotations, Hal $hal) : Hal
42
    {
43 11
        if (! empty($methodAnnotations)) {
44 7
            $hal = $this->linkAnnotation($body, $methodAnnotations, $hal);
45
        }
46 11
        if (isset($body['_links'])) {
47 3
            $hal = $this->bodyLink($body, $hal);
48
        }
49
50 11
        return $hal;
51
    }
52
53 7
    private function linkAnnotation(array $body, array $methodAnnotations, Hal $hal) : Hal
54
    {
55 7
        foreach ($methodAnnotations as $annotation) {
56 7
            if (! $annotation instanceof Link) {
57 3
                continue;
58
            }
59 5
            $uri = uri_template($annotation->href, $body);
60 5
            $reverseUri = $this->getReverseLink($uri);
61 5
            $hal->addLink($annotation->rel, $reverseUri);
62
        }
63
64 7
        return $hal;
65
    }
66
67 3
    private function bodyLink(array $body, Hal $hal) : Hal
68
    {
69 3
        foreach ($body['_links'] as $rel => $link) {
70 3
            $attr = $link;
71 3
            unset($attr['href']);
72 3
            $hal->addLink($rel, $link['href'], $attr);
73
        }
74
75 3
        return $hal;
76
    }
77
}
78