Passed
Pull Request — 1.x (#99)
by Akihito
10:41
created

DonutCommandInterceptor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
// phpcs:ignoreFile SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing -- for call_user_func_array
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\UnmatchedQuery;
8
use BEAR\Resource\AbstractUri;
9
use BEAR\Resource\ResourceObject;
10
use Ray\Aop\MethodInterceptor;
11
use Ray\Aop\MethodInvocation;
12
use ReflectionMethod;
13
14
use function array_values;
15
use function assert;
16
use function call_user_func_array;
17
use function get_class;
18
use function is_callable;
19
use function sprintf;
20
21
final class DonutCommandInterceptor implements MethodInterceptor
22
{
23
    /** @var DonutRepositoryInterface */
24
    private $repository;
25
26
    /** @var MatchQueryInterface */
27
    private $matchQuery;
28
29
    public function __construct(DonutRepositoryInterface $repository, MatchQueryInterface $matchQuery)
30
    {
31
        $this->repository = $repository;
32
        $this->matchQuery = $matchQuery;
33
    }
34
35
    public function invoke(MethodInvocation $invocation): ResourceObject
36
    {
37
        $ro = $invocation->proceed();
38
        assert($ro instanceof ResourceObject);
39
        $this->refreshDonutAndState($ro);
40
41
        return $ro;
42
    }
43
44
    public function refreshDonutAndState(ResourceObject $ro): void
45
    {
46
        $getQuery =($this->matchQuery)($ro);
47
        $delUri = clone $ro->uri;
48
        $delUri->query = $getQuery;
49
50
        // purge donut, resource state cache and etag
51
        $this->repository->purge($delUri);
52
        // update donut and create resource state
53
        $this->refresh($getQuery, $ro);
54
    }
55
56
    /**
57
     * @param array<string, mixed> $getQuery
58
     */
59
    private function refresh(array $getQuery, ResourceObject $ro): void
60
    {
61
        $ro->uri->query = $getQuery;
62
        $get = [$ro, 'onGet'];
63
        if (is_callable($get)) {
64
            call_user_func_array($get, array_values($getQuery));
65
        }
66
    }
67
}
68