Passed
Pull Request — 1.x (#117)
by Akihito
10:41 queued 07:55
created

AbstractDonutCacheInterceptor::invoke()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 17
c 3
b 0
f 0
nc 6
nop 1
dl 0
loc 31
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\Resource\Code;
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
use const E_USER_WARNING;
19
20
abstract class AbstractDonutCacheInterceptor implements MethodInterceptor
21
{
22
    protected const IS_ENTIRE_CONTENT_CACHEABLE = false;
23
24
    private DonutRepositoryInterface $donutRepository;
25
    private RefreshDonut $refreshDonut;
26
27
    public function __construct(DonutRepositoryInterface $donutRepository, RefreshDonut $refreshDonut)
28
    {
29
        $this->donutRepository = $donutRepository;
30
        $this->refreshDonut = $refreshDonut;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    final public function invoke(MethodInvocation $invocation)
37
    {
38
        if ($this->refreshDonut->refresh) {
39
            return $invocation->proceed();
40
        }
41
42
        $ro = $invocation->getThis();
43
        assert($ro instanceof ResourceObject);
44
45
        try {
46
            $maybeRo = $this->donutRepository->get($ro);
47
            if ($maybeRo instanceof ResourceObject) {
48
                return $maybeRo;
49
            }
50
        } catch (Throwable $e) { // @codeCoverageIgnoreStart
51
            // when cache server is down
52
            $this->triggerWarning($e);
53
54
            return $invocation->proceed(); // @codeCoverageIgnoreStartEnd
55
        }
56
57
        /** @var ResourceObject $ro */
58
        $ro = $invocation->proceed();
59
        // donut created in ResourceObject
60
        if (isset($ro->headers[Header::ETAG]) || $ro->code >= Code::BAD_REQUEST) {
61
            return $ro;
62
        }
63
64
        return static::IS_ENTIRE_CONTENT_CACHEABLE ?
65
            $this->donutRepository->putStatic($ro, null, null) :
66
            $this->donutRepository->putDonut($ro, null);
67
    }
68
69
    /**
70
     * @codeCoverageIgnore
71
     */
72
    private function triggerWarning(Throwable $e): void
73
    {
74
        trigger_error(sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_WARNING);
75
    }
76
}
77