src/Storefront/Framework/Routing/ResponseHeaderListener.php line 38

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing;
  3. use Shopware\Core\Framework\Log\Package;
  4. use Shopware\Core\PlatformRequest;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  9. /**
  10.  * @internal
  11.  */
  12. #[Package('storefront')]
  13. class ResponseHeaderListener implements EventSubscriberInterface
  14. {
  15.     private const REMOVAL_HEADERS = [
  16.         PlatformRequest::HEADER_VERSION_ID,
  17.         PlatformRequest::HEADER_LANGUAGE_ID,
  18.         PlatformRequest::HEADER_CONTEXT_TOKEN,
  19.         'Access-Control-Allow-Origin',
  20.         'Access-Control-Allow-Methods',
  21.         'Access-Control-Allow-Headers',
  22.         'Access-Control-Expose-Headers',
  23.     ];
  24.     /**
  25.      * @return array<string, array{0: string, 1: int}>
  26.      */
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             ResponseEvent::class => ['onResponse', -10],
  31.         ];
  32.     }
  33.     public function onResponse(ResponseEvent $event): void
  34.     {
  35.         $response $event->getResponse();
  36.         /** @var list<string> $scopes */
  37.         $scopes $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  38.         if (!\in_array(StorefrontRouteScope::ID$scopestrue) && !$response instanceof StorefrontResponse) {
  39.             return;
  40.         }
  41.         $this->manipulateStorefrontHeader($event->getRequest(), $response);
  42.     }
  43.     private function manipulateStorefrontHeader(Request $requestResponse $response): void
  44.     {
  45.         $this->removeHeaders($response);
  46.         $this->addNoStoreHeader($request$response);
  47.     }
  48.     private function removeHeaders(Response $response): void
  49.     {
  50.         foreach (self::REMOVAL_HEADERS as $headerKey) {
  51.             $response->headers->remove($headerKey);
  52.         }
  53.     }
  54.     private function addNoStoreHeader(Request $requestResponse $response): void
  55.     {
  56.         if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_NO_STORE)) {
  57.             return;
  58.         }
  59.         $response->setMaxAge(0);
  60.         $response->headers->addCacheControlDirective('no-cache');
  61.         $response->headers->addCacheControlDirective('no-store');
  62.         $response->headers->addCacheControlDirective('must-revalidate');
  63.         $response->setExpires(new \DateTime('@0'));
  64.     }
  65. }