CacheInterceptor::invoke()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0131

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
c 2
b 0
f 0
nc 8
nop 1
dl 0
loc 31
rs 8.9777
ccs 13
cts 14
cp 0.9286
crap 6.0131
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\QueryRepository\Exception\LogicException;
8
use BEAR\Resource\ResourceObject;
9
use Override;
10
use Ray\Aop\MethodInterceptor;
11
use Ray\Aop\MethodInvocation;
12
use Throwable;
13
14
use function assert;
15
use function sprintf;
16
use function trigger_error;
17
18
use const E_USER_WARNING;
19
20
final class CacheInterceptor implements MethodInterceptor
21
{
22
    public function __construct(
23
        private readonly QueryRepositoryInterface $repository,
24
    ) {
25
    }
26
27
    /**
28
     * {@inheritDoc}
29
     */
30
    #[Override]
31
    public function invoke(MethodInvocation $invocation)
32
    {
33 14
        $ro = $invocation->getThis();
34
        assert($ro instanceof ResourceObject);
35
        try {
36
            $state = $this->repository->get($ro->uri);
37
        } catch (Throwable $e) {
38 14
            $this->triggerWarning($e);
39 14
40 14
            return $invocation->proceed(); // @codeCoverageIgnore
41 14
        }
42
43
        if ($state instanceof ResourceState) {
44
            $state->visit($ro);
45
46 12
            return $ro;
47
        }
48 12
49
        /** @psalm-suppress MixedAssignment */
50 12
        $ro = $invocation->proceed();
51 12
        assert($ro instanceof ResourceObject);
52 9
        try {
53
            $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
54 9
        } catch (LogicException $e) {
55
            throw $e;
56
        } catch (Throwable $e) {  // @codeCoverageIgnore
57
            $this->triggerWarning($e); // @codeCoverageIgnore
58 12
        }
59 12
60
        return $ro;
61
    }
62
63
    /**
64
     * Trigger warning
65 12
     *
66
     * When the cache server is down, it will issue a warning rather than an exception to continue service.
67
     *
68
     * @codeCoverageIgnore
69
     */
70
    private function triggerWarning(Throwable $e): void
71
    {
72
        $message = sprintf('%s: %s in %s:%s', $e::class, $e->getMessage(), $e->getFile(), $e->getLine());
73
        trigger_error($message, E_USER_WARNING);
74
    }
75
}
76