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

AbstractDonutCacheInterceptor::triggerWarning()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

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 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\Resource\ResourceObject;
8
use Ray\Aop\MethodInterceptor;
9
use Ray\Aop\MethodInvocation;
10
use Throwable;
11
12
use function assert;
13
use function get_class;
14
use function sprintf;
15
use function trigger_error;
16
17
use const E_USER_WARNING;
18
19
abstract class AbstractDonutCacheInterceptor implements MethodInterceptor
20
{
21
    protected const IS_ENTIRE_CONTENT_CACHEABLE = false;
22
23
    /** @var DonutRepositoryInterface */
24
    private $donutRepository;
25
26
    public function __construct(DonutRepositoryInterface $donutRepository)
27
    {
28
        $this->donutRepository = $donutRepository;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    final public function invoke(MethodInvocation $invocation)
35
    {
36
        $ro = $invocation->getThis();
37
        assert($ro instanceof ResourceObject);
38
        try {
39
            $maybeRo = $this->donutRepository->get($ro);
40
            if ($maybeRo instanceof ResourceObject) {
41
                return $maybeRo;
42
            }
43
        } catch (Throwable $e) { // @codeCoverageIgnoreStart
44
            // when cache server is down
45
            $this->triggerWarning($e);
46
47
            return $invocation->proceed(); // @codeCoverageIgnoreStartEnd
48
        }
49
50
        /** @var ResourceObject $ro */
51
        $ro = $invocation->proceed();
52
        if (isset($ro->headers[Header::ETAG])) {
53
            return $ro; // donut created in ResourceObject
54
        }
55
56
        return static::IS_ENTIRE_CONTENT_CACHEABLE ?
57
            $this->donutRepository->putStatic($ro, null, null) :
58
            $this->donutRepository->putDonut($ro, null);
59
    }
60
61
    /**
62
     * @codeCoverageIgnore
63
     */
64
    private function triggerWarning(Throwable $e): void
65
    {
66
        trigger_error(sprintf('%s: %s in %s:%s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_WARNING);
67
    }
68
}
69