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