Completed
Push — 1.x ( 6eac35...9e7ca8 )
by Akihito
19s queued 15s
created

CacheInterceptor::triggerWarning()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
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 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 24
use const E_USER_WARNING;
19
20
final class CacheInterceptor implements MethodInterceptor
21 24
{
22 24
    public function __construct(
23
        private readonly QueryRepositoryInterface $repository,
24
    ) {
25
    }
26
27 22
    /**
28
     * {@inheritDoc}
29
     */
30 22
    #[Override]
31 22
    public function invoke(MethodInvocation $invocation)
32 22
    {
33 12
        $ro = $invocation->getThis();
34
        assert($ro instanceof ResourceObject);
35 12
        try {
36
            $state = $this->repository->get($ro->uri);
37
        } catch (Throwable $e) {
38
            $this->triggerWarning($e);
39 22
40 22
            return $invocation->proceed(); // @codeCoverageIgnore
41 1
        }
42 1
43
        if ($state instanceof ResourceState) {
44 1
            $state->visit($ro);
45
46
            return $ro;
47 21
        }
48
49
        /** @psalm-suppress MixedAssignment */
50
        $ro = $invocation->proceed();
51
        assert($ro instanceof ResourceObject);
52
        try {
53
            $ro->code === 200 ? $this->repository->put($ro) : $this->repository->purge($ro->uri);
54
        } catch (LogicException $e) {
55
            throw $e;
56
        } catch (Throwable $e) {  // @codeCoverageIgnore
57
            $this->triggerWarning($e); // @codeCoverageIgnore
58
        }
59
60
        return $ro;
61
    }
62
63
    /**
64
     * Trigger warning
65
     *
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