HttpCacheInterceptor::invoke()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 8
nop 1
dl 0
loc 17
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\QueryRepository;
6
7
use BEAR\RepositoryModule\Annotation\AbstractCacheControl;
8
use BEAR\RepositoryModule\Annotation\HttpCache;
9
use BEAR\RepositoryModule\Annotation\NoHttpCache;
10
use BEAR\Resource\ResourceObject;
11
use Override;
12
use Ray\Aop\MethodInterceptor;
13
use Ray\Aop\MethodInvocation;
14
15
use function assert;
16
17
/**
18
 * Interceptor for HTTP Cache-Control header with #[HttpCache] or #[NoHttpCache]
19
 *
20
 * Bound to onGet methods of classes marked with #[HttpCache] or #[NoHttpCache].
21
 * Sets the Cache-Control header based on attribute configuration for HTTP caching.
22
 *
23
 * @see \BEAR\RepositoryModule\Annotation\HttpCache
24
 * @see \BEAR\RepositoryModule\Annotation\NoHttpCache
25
 * @see https://bearsunday.github.io/manuals/1.0/en/cache.html
26
 */
27
final class HttpCacheInterceptor implements MethodInterceptor
28
{
29
    /**
30
     * {@inheritDoc}
31
     */
32
    #[Override]
33
    public function invoke(MethodInvocation $invocation)
34
    {
35
        $class = $invocation->getMethod()->getDeclaringClass();
36
        $attributes = $class->getAttributes(HttpCache::class);
37
        if (empty($attributes)) {
38
            $attributes = $class->getAttributes(NoHttpCache::class);
39
        }
40
41
        $cacheControl = isset($attributes[0]) ? $attributes[0]->newInstance() : null;
42
        $ro = $invocation->proceed();
43
        assert($ro instanceof ResourceObject);
44
        if ($ro->code === 200 && $cacheControl instanceof AbstractCacheControl) {
45
            $ro->headers[Header::CACHE_CONTROL] = (string) $cacheControl;
46
        }
47
48
        return $ro;
49
    }
50
}
51