|
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
|
|
|
public function __construct(Reader $reader) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->reader = $reader; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* {@inheritdoc} |
|
26
|
|
|
* |
|
27
|
|
|
* @throws LinkException |
|
28
|
|
|
*/ |
|
29
|
|
|
public function href(string $rel, AbstractRequest $request, array $query) : array |
|
30
|
|
|
{ |
|
31
|
|
|
$classMethod = 'on' . ucfirst($request->method); |
|
32
|
|
|
$annotations = $this->reader->getMethodAnnotations(new \ReflectionMethod(get_class($request->resourceObject), $classMethod)); |
|
33
|
|
|
foreach ($annotations as $annotation) { |
|
34
|
|
|
if ($this->isValidLinkAnnotation($annotation, $rel)) { |
|
35
|
|
|
return $this->getMethodUri($request, $query, $annotation); |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
throw new LinkException("rel:{$rel} class:" . get_class($request->resourceObject), 500); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
private function isValidLinkAnnotation(object $annotation, string $rel) : bool |
|
43
|
|
|
{ |
|
44
|
|
|
return $annotation instanceof LinkAnnotation && $annotation->rel !== null && $annotation->rel === $rel; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @param array<string, mixed> $query |
|
49
|
|
|
* |
|
50
|
|
|
* @return array{0:string, 1:string} |
|
|
|
|
|
|
51
|
|
|
*/ |
|
52
|
|
|
private function getMethodUri(AbstractRequest $request, array $query, LinkAnnotation $annotation) : array |
|
53
|
|
|
{ |
|
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.