BoostResponseSubscriber.php in Boost 8
File
src/EventSubscriber/BoostResponseSubscriber.php
View source
<?php
namespace Drupal\boost\EventSubscriber;
use Drupal\boost\BoostCache;
use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Render\AttachmentsResponseProcessorInterface;
use Drupal\Core\Session\AccountProxy;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BoostResponseSubscriber implements EventSubscriberInterface {
protected $htmlResponseAttachmentsProcessor;
protected $account;
public function __construct(AttachmentsResponseProcessorInterface $html_response_attachments_processor, AccountProxy $account) {
$this->boostCache = new BoostCache();
$this->htmlResponseAttachmentsProcessor = $html_response_attachments_processor;
$this->account = $account;
}
public static function getSubscribedEvents() {
return array(
KernelEvents::REQUEST => array(
array(
'onRequest',
100,
),
),
KernelEvents::RESPONSE => array(
array(
'onRespond',
-100,
),
),
);
}
public function onRequest(GetResponseEvent $event) {
if ($this->account
->isAuthenticated()) {
return;
}
$method = $event
->getRequest()
->getMethod();
if ($method == 'POST') {
$this->boostCache
->delete();
}
if ($method != 'GET') {
return;
}
if ($content = $this->boostCache
->retrieve()) {
$response = new Response();
$response
->setContent($content);
$response
->setStatusCode(Response::HTTP_OK);
$response->headers
->set('X-Boost-Cache', 'partial');
$event
->setResponse($response);
}
}
public function onRespond(FilterResponseEvent $event) {
if ($this->account
->isAuthenticated()) {
return;
}
$response = $event
->getResponse();
if (!$response instanceof HtmlResponse) {
return;
}
if ($response
->isRedirect() || $response
->isForbidden() || $response
->isNotFound()) {
return;
}
$this->htmlResponseAttachmentsProcessor
->processAttachments($response);
$content = $response
->getContent();
$this->boostCache
->index($content);
}
}