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

CacheInterceptor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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