platform/src/Storefront/Framework/Routing/ResponseHeaderListener.php line 22

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing;
  3. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  4. use Shopware\Core\PlatformRequest;
  5. use Shopware\Storefront\Framework\Routing\Annotation\NoStore;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. class ResponseHeaderListener
  8. {
  9.     private const REMOVAL_HEADERS = [
  10.         PlatformRequest::HEADER_VERSION_ID,
  11.         PlatformRequest::HEADER_LANGUAGE_ID,
  12.         PlatformRequest::HEADER_CONTEXT_TOKEN,
  13.         'Access-Control-Allow-Origin',
  14.         'Access-Control-Allow-Methods',
  15.         'Access-Control-Allow-Headers',
  16.         'Access-Control-Expose-Headers',
  17.     ];
  18.     public function __invoke(ResponseEvent $event): void
  19.     {
  20.         /** @var RouteScope|null $routeScope */
  21.         $routeScope $event->getRequest()->attributes->get('_routeScope');
  22.         if ($routeScope === null || !$routeScope->hasScope('storefront')) {
  23.             return;
  24.         }
  25.         $this->removeHeaders($event);
  26.         $this->addNoStoreHeader($event);
  27.     }
  28.     private function removeHeaders(ResponseEvent $event): void
  29.     {
  30.         foreach (self::REMOVAL_HEADERS as $headerKey) {
  31.             $event->getResponse()->headers->remove($headerKey);
  32.         }
  33.     }
  34.     private function addNoStoreHeader(ResponseEvent $event): void
  35.     {
  36.         if (!$event->getRequest()->attributes->has('_' NoStore::ALIAS)) {
  37.             return;
  38.         }
  39.         $event->getResponse()->setMaxAge(0);
  40.         $event->getResponse()->headers->addCacheControlDirective('no-cache');
  41.         $event->getResponse()->headers->addCacheControlDirective('no-store');
  42.         $event->getResponse()->headers->addCacheControlDirective('must-revalidate');
  43.         $event->getResponse()->setExpires(new \DateTime('@0'));
  44.     }
  45. }