Completed
Pull Request — 1.x (#209)
by Akihito
12:16 queued 11:04
created

Anchor::getMethodUri()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 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 Doctrine\Common\Annotations\Reader;
10
use function get_class;
11
12
final class Anchor implements AnchorInterface
13
{
14
    /**
15
     * @var Reader
16
     */
17
    private $reader;
18
19 49
    public function __construct(Reader $reader)
20
    {
21 49
        $this->reader = $reader;
22 49
    }
23
24
    /**
25
     * {@inheritdoc}
26
     *
27
     * @throws LinkException
28
     */
29 5
    public function href(string $rel, AbstractRequest $request, array $query) : array
30
    {
31 5
        $classMethod = 'on' . ucfirst($request->method);
32 5
        $annotations = $this->reader->getMethodAnnotations(new \ReflectionMethod(get_class($request->resourceObject), $classMethod));
33 5
        foreach ($annotations as $annotation) {
34 5
            if ($this->isValidLinkAnnotation($annotation, $rel)) {
35 5
                return $this->getMethodUri($request, $query, $annotation);
36
            }
37
        }
38
39 1
        throw new LinkException("rel:{$rel} class:" . get_class($request->resourceObject), 500);
40
    }
41
42 5
    private function isValidLinkAnnotation(object $annotation, string $rel) : bool
43
    {
44 5
        return $annotation instanceof LinkAnnotation && $annotation->rel !== null && $annotation->rel === $rel;
45
    }
46
47 4
    /**
48
     * @param array<string, mixed> $query
49 4
     *
50 4
     * @return array{0:string, 1:string}
0 ignored issues
show
Documentation introduced by
The doc-type array{0:string, could not be parsed: Unknown type name "array{0:string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
51 4
     */
52
    private function getMethodUri(AbstractRequest $request, array $query, LinkAnnotation $annotation) : array
53 4
    {
54
        $body = $request->resourceObject->body;
55
        $query = is_array($body) ? array_merge($body, $query) : [];
56
        $uri = uri_template($annotation->href, $query);
57
58
        return [$annotation->method, $uri];
59
    }
60
}
61