Completed
Push — 1.x ( 246016...0c7587 )
by Akihito
03:54 queued 03:52
created

Anchor   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 2 Features 0
Metric Value
eloc 12
dl 0
loc 41
ccs 17
cts 17
cp 1
rs 10
c 4
b 2
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidLinkAnnotation() 0 4 3
A href() 0 13 3
A getMethodUri() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Annotation\Link as LinkAnnotation;
8
use BEAR\Resource\Exception\LinkException;
9
use Ray\Aop\ReflectionMethod;
10
11
use function array_merge;
12
use function assert;
13
use function is_array;
14
use function ucfirst;
15
use function uri_template;
16
17
final class Anchor implements AnchorInterface
18
{
19 49
    /**
20
     * {@inheritDoc}
21 49
     *
22 49
     * @throws LinkException
23
     */
24
    public function href(string $rel, AbstractRequest $request, array $query): array
25
    {
26
        $classMethod = 'on' . ucfirst($request->method);
27
        $annotations = (new ReflectionMethod($request->resourceObject::class, $classMethod))->getAnnotations();
28
        foreach ($annotations as $annotation) {
29 5
            if ($this->isValidLinkAnnotation($annotation, $rel)) {
30
                assert($annotation instanceof LinkAnnotation);
31 5
32 5
                return $this->getMethodUri($request, $query, $annotation);
33 5
            }
34 5
        }
35 5
36
        throw new LinkException("rel:{$rel} class:" . $request->resourceObject::class, 500);
37
    }
38
39 1
    private function isValidLinkAnnotation(object $annotation, string $rel): bool
40
    {
41
        /** @psalm-suppress RedundantConditionGivenDocblockType */
42 5
        return $annotation instanceof LinkAnnotation && $annotation->rel !== null && $annotation->rel === $rel;
43
    }
44 5
45
    /**
46
     * @param array<string, mixed> $query
47 4
     *
48
     * @return array{0:string, 1:string}
49 4
     */
50 4
    private function getMethodUri(AbstractRequest $request, array $query, LinkAnnotation $annotation): array
51 4
    {
52
        /** @var array|mixed $body */
53 4
        $body = $request->resourceObject->body;
54
        $query = is_array($body) ? array_merge($body, $query) : [];
55
        $uri = uri_template($annotation->href, $query);
56
57
        return [$annotation->method, $uri];
58
    }
59
}
60