src/EventSubscriber/RequestCacheSubscriber.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Services\RequestCacheService;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. class RequestCacheSubscriber implements EventSubscriberInterface {
  8.     /**
  9.      * @var RequestCacheService
  10.      */
  11.     protected $requestCacheService;
  12.     /**
  13.      * @var bool
  14.      */
  15.     protected $supportsRequest false;
  16.     /**
  17.      * @var bool
  18.      */
  19.     protected $usedCache false;
  20.     /**
  21.      * RequestCacheSubscriber constructor.
  22.      * @param RequestCacheService $requestCacheService
  23.      */
  24.     public function __construct(RequestCacheService $requestCacheService) {
  25.         $this->requestCacheService $requestCacheService;
  26.     }
  27.     public static function getSubscribedEvents(): array {
  28.         return [
  29.             'kernel.request' => 'onKernelRequest',
  30.             'kernel.response' => 'onKernelResponse',
  31.         ];
  32.     }
  33.     public function onKernelRequest(RequestEvent $event) {
  34.         if (!$event->isMasterRequest()) {
  35.             return;
  36.         }
  37.         $request $event->getRequest();
  38.         $this->supportsRequest $this->requestCacheService->supports($request);
  39.         if (!$this->supportsRequest) {
  40.             return;
  41.         }
  42.         $jsonResponse $this->requestCacheService->getCachedResponse($request);
  43.         if (isset($jsonResponse)) {
  44.             $this->usedCache true;
  45.             $event->setResponse($jsonResponse);
  46.         }
  47.     }
  48.     public function onKernelResponse(ResponseEvent $event) {
  49.         if (!$this->supportsRequest) {
  50.             return;
  51.         }
  52.         $response $event->getResponse();
  53.         // Only cache success responses
  54.         if ($response->getStatusCode() !== 200) {
  55.             return;
  56.         }
  57.         // Prevent re-writing in kernel response
  58.         if ($this->usedCache) {
  59.             return;
  60.         }
  61.         $this->requestCacheService->cacheResponse($event->getRequest(), $response);
  62.     }
  63. }