BypassCacheListener   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 39
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A onKernelRequest() 0 13 4
A getSubscribedEvents() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MovingImage\Bundle\VMProApiBundle\EventListener;
6
7
use MovingImage\Bundle\VMProApiBundle\Decorator\BlackholeCacheItemPoolDecorator;
8
use MovingImage\Client\VMPro\ApiClient;
9
use MovingImage\Client\VMPro\ApiClient\AbstractApiClient;
10
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
11
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
12
use Symfony\Component\HttpKernel\KernelEvents;
13
14
/**
15
 * This listener kicks in only if the `cache_bypass_argument` bundle config option is set.
16
 * If the request contains an argument matching the value configured in the aforementioned config option
17
 * and the value of that argument evaluates to true, this listener will modify the cache pool implementation
18
 * used by the VMPro API client, by decorating it with a blackhole cache implementation:
19
 * one that stores responses to cache, but never returns a hit.
20
 */
21
class BypassCacheListener implements EventSubscriberInterface
22
{
23
    /**
24
     * @var ApiClient
25
     */
26
    private $apiClient;
27
28
    /**
29
     * @var string|null
30
     */
31
    private $cacheBypassArgument;
32
33
    public function __construct(ApiClient $apiClient, ?string $cacheBypassArgument = null)
34
    {
35 18
        $this->apiClient = $apiClient;
36
        $this->cacheBypassArgument = $cacheBypassArgument;
37 18
    }
38 18
39 18
    public function onKernelRequest(GetResponseEvent $event): void
40
    {
41
        if (is_null($this->cacheBypassArgument)) {
42
            return;
43
        }
44 18
45
        $request = $event->getRequest();
46 18
        if ($request->get($this->cacheBypassArgument) || $request->cookies->get($this->cacheBypassArgument)) {
47 10
            /** @var AbstractApiClient $apiClient */
48
            $cachePool = new BlackholeCacheItemPoolDecorator($this->apiClient->getCacheItemPool());
49
            $this->apiClient->setCacheItemPool($cachePool);
50 8
        }
51 8
    }
52
53 8
    public static function getSubscribedEvents(): array
54 8
    {
55 8
        return [
56 8
            KernelEvents::REQUEST => 'onKernelRequest',
57
        ];
58
    }
59
}
60