AbstractDonutCacheInterceptor::triggerWarning()   A
last analyzed

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\Code;
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
use const E_USER_WARNING;
19
20
abstract class AbstractDonutCacheInterceptor implements MethodInterceptor
21
{
22
    protected const IS_ENTIRE_CONTENT_CACHEABLE = false;
23
24
    public function __construct(
25
        private readonly DonutRepositoryInterface $donutRepository,
26
    ) {
27
    }
28
29
    /**
30
     * {@inheritDoc}
31
     */
32
    #[Override]
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