AbstractDonutCacheInterceptor::invoke()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 15
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 26
rs 9.2222
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 sprintf;
15
use function trigger_error;
16
17
use const E_USER_WARNING;
18
19
abstract class AbstractDonutCacheInterceptor implements MethodInterceptor
20
{
21
    // @phpcs:ignore SlevomatCodingStandard.TypeHints.UselessConstantTypeHint.UselessDocComment
22
    /** @var bool */
23
    protected const IS_ENTIRE_CONTENT_CACHEABLE = false;
24
25
    public function __construct(
26
        private readonly DonutRepositoryInterface $donutRepository,
27
    ) {
28
    }
29
30
    /**
31
     * {@inheritDoc}
32
     */
33
    final public function invoke(MethodInvocation $invocation)
34
    {
35
        $ro = $invocation->getThis();
36
        assert($ro instanceof ResourceObject);
37
        try {
38
            $maybeRo = $this->donutRepository->get($ro);
39
            if ($maybeRo instanceof ResourceObject) {
40
                return $maybeRo;
41
            }
42
        } catch (Throwable $e) { // @codeCoverageIgnoreStart
43
            // when cache server is down
44
            $this->triggerWarning($e);
45
46
            return $invocation->proceed(); // @codeCoverageIgnoreEnd
47
        }
48
49
        /** @var ResourceObject $ro */
50
        $ro = $invocation->proceed();
51
        // donut created in ResourceObject
52
        if (isset($ro->headers[Header::ETAG]) || $ro->code >= Code::BAD_REQUEST) {
53
            return $ro;
54
        }
55
56
        return static::IS_ENTIRE_CONTENT_CACHEABLE ? // phpcs:ignore - not "self"
57
            $this->donutRepository->putStatic($ro, null, null) :
58
            $this->donutRepository->putDonut($ro, null);
59
    }
60
61
    /** @codeCoverageIgnore */
62
    private function triggerWarning(Throwable $e): void
63
    {
64
        trigger_error(sprintf('%s: %s in %s:%s', $e::class, $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_WARNING);
65
    }
66
}
67