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

Anchor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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