CacheInterceptor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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