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} |
|
|
|
|
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
|
|
|
|
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.