<?php
namespace App\EventSubscriber;
use App\Services\RequestCacheService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class RequestCacheSubscriber implements EventSubscriberInterface {
/**
* @var RequestCacheService
*/
protected $requestCacheService;
/**
* @var bool
*/
protected $supportsRequest = false;
/**
* @var bool
*/
protected $usedCache = false;
/**
* RequestCacheSubscriber constructor.
* @param RequestCacheService $requestCacheService
*/
public function __construct(RequestCacheService $requestCacheService) {
$this->requestCacheService = $requestCacheService;
}
public static function getSubscribedEvents(): array {
return [
'kernel.request' => 'onKernelRequest',
'kernel.response' => 'onKernelResponse',
];
}
public function onKernelRequest(RequestEvent $event) {
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$this->supportsRequest = $this->requestCacheService->supports($request);
if (!$this->supportsRequest) {
return;
}
$jsonResponse = $this->requestCacheService->getCachedResponse($request);
if (isset($jsonResponse)) {
$this->usedCache = true;
$event->setResponse($jsonResponse);
}
}
public function onKernelResponse(ResponseEvent $event) {
if (!$this->supportsRequest) {
return;
}
$response = $event->getResponse();
// Only cache success responses
if ($response->getStatusCode() !== 200) {
return;
}
// Prevent re-writing in kernel response
if ($this->usedCache) {
return;
}
$this->requestCacheService->cacheResponse($event->getRequest(), $response);
}
}