RefreshAnnotatedCommand::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\RepositoryModule\Annotation\AbstractCommand;
8
use BEAR\RepositoryModule\Annotation\Purge;
9
use BEAR\RepositoryModule\Annotation\Refresh;
10
use BEAR\Resource\ResourceInterface;
11
use BEAR\Resource\ResourceObject;
12
use BEAR\Resource\Uri;
13
use Override;
14
use Ray\Aop\MethodInvocation;
15
16
use function is_array;
17
use function uri_template;
18
19
final class RefreshAnnotatedCommand implements CommandInterface
20
{
21
    public function __construct(
22
        private readonly QueryRepositoryInterface $repository,
23
        private readonly ResourceInterface $resource,
24
    ) {
25
    }
26
27
    #[Override]
28
    public function command(MethodInvocation $invocation, ResourceObject $ro): void
29
    {
30
        $method = $invocation->getMethod();
31
        $annotations = $method->getAnnotations();
32
        foreach ($annotations as $annotation) {
33
            $this->request($ro, $annotation);
34
        }
35
    }
36
37
    private function getUri(ResourceObject $ro, AbstractCommand $annotation): string
38
    {
39
        $body = is_array($ro->body) ? $ro->body : [];
40
        $query = $body + $ro->uri->query;
41
42
        return uri_template($annotation->uri, $query);
43
    }
44
45
    private function request(ResourceObject $ro, object $annotation): void
46
    {
47
        if (! $annotation instanceof AbstractCommand) {
48
            return;
49
        }
50
51
        $uri = new Uri($this->getUri($ro, $annotation));
52
        if ($annotation instanceof Purge) {
53
            $this->repository->purge($uri);
54
        }
55
56
        if ($annotation instanceof Refresh) {
57
            $this->repository->purge($uri);
58
            $ro = $this->resource->get((string) $uri);
59
            $this->repository->put($ro);
60
        }
61
    }
62
}
63