vendor/shopware/storefront/Framework/Cache/CacheResponseSubscriber.php line 88

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Cache;
  3. use Shopware\Core\Checkout\Cart\Cart;
  4. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  5. use Shopware\Core\Framework\Adapter\Cache\CacheStateSubscriber;
  6. use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
  7. use Shopware\Core\PlatformRequest;
  8. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService;
  9. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  10. use Shopware\Storefront\Framework\Cache\Annotation\HttpCache;
  11. use Shopware\Storefront\Framework\Routing\MaintenanceModeResolver;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Cookie;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\RequestEvent;
  17. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. /**
  20.  * @deprecated tag:v6.5.0 - reason:becomes-internal - EventSubscribers will become internal in v6.5.0
  21.  */
  22. class CacheResponseSubscriber implements EventSubscriberInterface
  23. {
  24.     public const STATE_LOGGED_IN CacheStateSubscriber::STATE_LOGGED_IN;
  25.     public const STATE_CART_FILLED CacheStateSubscriber::STATE_CART_FILLED;
  26.     public const CURRENCY_COOKIE 'sw-currency';
  27.     public const CONTEXT_CACHE_COOKIE 'sw-cache-hash';
  28.     public const SYSTEM_STATE_COOKIE 'sw-states';
  29.     public const INVALIDATION_STATES_HEADER 'sw-invalidation-states';
  30.     private const CORE_HTTP_CACHED_ROUTES = [
  31.         'api.acl.privileges.get',
  32.     ];
  33.     private bool $reverseProxyEnabled;
  34.     private CartService $cartService;
  35.     private int $defaultTtl;
  36.     private bool $httpCacheEnabled;
  37.     private MaintenanceModeResolver $maintenanceResolver;
  38.     private ?string $staleWhileRevalidate;
  39.     private ?string $staleIfError;
  40.     /**
  41.      * @internal
  42.      */
  43.     public function __construct(
  44.         CartService $cartService,
  45.         int $defaultTtl,
  46.         bool $httpCacheEnabled,
  47.         MaintenanceModeResolver $maintenanceModeResolver,
  48.         bool $reverseProxyEnabled,
  49.         ?string $staleWhileRevalidate,
  50.         ?string $staleIfError
  51.     ) {
  52.         $this->cartService $cartService;
  53.         $this->defaultTtl $defaultTtl;
  54.         $this->httpCacheEnabled $httpCacheEnabled;
  55.         $this->maintenanceResolver $maintenanceModeResolver;
  56.         $this->reverseProxyEnabled $reverseProxyEnabled;
  57.         $this->staleWhileRevalidate $staleWhileRevalidate;
  58.         $this->staleIfError $staleIfError;
  59.     }
  60.     /**
  61.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  62.      */
  63.     public static function getSubscribedEvents()
  64.     {
  65.         return [
  66.             KernelEvents::REQUEST => 'addHttpCacheToCoreRoutes',
  67.             KernelEvents::RESPONSE => [
  68.                 ['setResponseCache', -1500],
  69.             ],
  70.             BeforeSendResponseEvent::class => 'updateCacheControlForBrowser',
  71.         ];
  72.     }
  73.     public function addHttpCacheToCoreRoutes(RequestEvent $event): void
  74.     {
  75.         $request $event->getRequest();
  76.         $route $request->attributes->get('_route');
  77.         if (\in_array($routeself::CORE_HTTP_CACHED_ROUTEStrue)) {
  78.             $request->attributes->set('_' HttpCache::ALIAS, [new HttpCache([])]);
  79.         }
  80.     }
  81.     public function setResponseCache(ResponseEvent $event): void
  82.     {
  83.         if (!$this->httpCacheEnabled) {
  84.             return;
  85.         }
  86.         $response $event->getResponse();
  87.         $request $event->getRequest();
  88.         if (!$this->maintenanceResolver->shouldBeCached($request)) {
  89.             return;
  90.         }
  91.         $context $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  92.         if (!$context instanceof SalesChannelContext) {
  93.             return;
  94.         }
  95.         $route $request->attributes->get('_route');
  96.         if ($route === 'frontend.checkout.configure') {
  97.             $this->setCurrencyCookie($request$response);
  98.         }
  99.         $cart $this->cartService->getCart($context->getToken(), $context);
  100.         $states $this->updateSystemState($cart$context$request$response);
  101.         // We need to allow it on login, otherwise the state is wrong
  102.         if (!($route === 'frontend.account.login' || $request->getMethod() === Request::METHOD_GET)) {
  103.             return;
  104.         }
  105.         if ($context->getCustomer() || $cart->getLineItems()->count() > 0) {
  106.             $newValue $this->buildCacheHash($context);
  107.             if ($request->cookies->get(self::CONTEXT_CACHE_COOKIE'') !== $newValue) {
  108.                 $cookie Cookie::create(self::CONTEXT_CACHE_COOKIE$newValue);
  109.                 $cookie->setSecureDefault($request->isSecure());
  110.                 $response->headers->setCookie($cookie);
  111.             }
  112.         } elseif ($request->cookies->has(self::CONTEXT_CACHE_COOKIE)) {
  113.             $response->headers->removeCookie(self::CONTEXT_CACHE_COOKIE);
  114.             $response->headers->clearCookie(self::CONTEXT_CACHE_COOKIE);
  115.         }
  116.         $config $request->attributes->get('_' HttpCache::ALIAS);
  117.         if (empty($config)) {
  118.             return;
  119.         }
  120.         /** @var HttpCache $cache */
  121.         $cache array_shift($config);
  122.         if ($this->hasInvalidationState($cache$states)) {
  123.             return;
  124.         }
  125.         $maxAge $cache->getMaxAge() ?? $this->defaultTtl;
  126.         $response->setSharedMaxAge($maxAge);
  127.         $response->headers->addCacheControlDirective('must-revalidate');
  128.         $response->headers->set(
  129.             self::INVALIDATION_STATES_HEADER,
  130.             implode(','$cache->getStates())
  131.         );
  132.         if ($this->staleIfError !== null) {
  133.             $response->headers->addCacheControlDirective('stale-if-error'$this->staleIfError);
  134.         }
  135.         if ($this->staleWhileRevalidate !== null) {
  136.             $response->headers->addCacheControlDirective('stale-while-revalidate'$this->staleWhileRevalidate);
  137.         }
  138.     }
  139.     /**
  140.      * In the default HttpCache implementation the reverse proxy cache is implemented too in PHP and triggered before the response is send to the client. We don't need to send the "real" cache-control headers to the end client (browser/cloudflare).
  141.      * If a external reverse proxy cache is used we still need to provide the actual cache-control, so the external system can cache the system correctly and set the cache-control again to
  142.      */
  143.     public function updateCacheControlForBrowser(BeforeSendResponseEvent $event): void
  144.     {
  145.         if ($this->reverseProxyEnabled) {
  146.             return;
  147.         }
  148.         $response $event->getResponse();
  149.         $noStore $response->headers->getCacheControlDirective('no-store');
  150.         // We don't want that the client will cache the website, if no reverse proxy is configured
  151.         $response->headers->remove('cache-control');
  152.         $response->setPrivate();
  153.         if ($noStore) {
  154.             $response->headers->addCacheControlDirective('no-store');
  155.         } else {
  156.             $response->headers->addCacheControlDirective('no-cache');
  157.         }
  158.     }
  159.     /**
  160.      * @param list<string> $states
  161.      */
  162.     private function hasInvalidationState(HttpCache $cache, array $states): bool
  163.     {
  164.         foreach ($states as $state) {
  165.             if (\in_array($state$cache->getStates(), true)) {
  166.                 return true;
  167.             }
  168.         }
  169.         return false;
  170.     }
  171.     private function buildCacheHash(SalesChannelContext $context): string
  172.     {
  173.         return md5(json_encode([
  174.             $context->getRuleIds(),
  175.             $context->getContext()->getVersionId(),
  176.             $context->getCurrency()->getId(),
  177.             $context->getCustomer() ? 'logged-in' 'not-logged-in',
  178.         ], \JSON_THROW_ON_ERROR));
  179.     }
  180.     /**
  181.      * System states can be used to stop caching routes at certain states. For example,
  182.      * the checkout routes are no longer cached if the customer has products in the cart or is logged in.
  183.      *
  184.      * @return list<string>
  185.      */
  186.     private function updateSystemState(Cart $cartSalesChannelContext $contextRequest $requestResponse $response): array
  187.     {
  188.         $states $this->getSystemStates($request$context$cart);
  189.         if (empty($states)) {
  190.             if ($request->cookies->has(self::SYSTEM_STATE_COOKIE)) {
  191.                 $response->headers->removeCookie(self::SYSTEM_STATE_COOKIE);
  192.                 $response->headers->clearCookie(self::SYSTEM_STATE_COOKIE);
  193.             }
  194.             return [];
  195.         }
  196.         $newStates implode(','$states);
  197.         if ($request->cookies->get(self::SYSTEM_STATE_COOKIE) !== $newStates) {
  198.             $cookie Cookie::create(self::SYSTEM_STATE_COOKIE$newStates);
  199.             $cookie->setSecureDefault($request->isSecure());
  200.             $response->headers->setCookie($cookie);
  201.         }
  202.         return $states;
  203.     }
  204.     /**
  205.      * @return list<string>
  206.      */
  207.     private function getSystemStates(Request $requestSalesChannelContext $contextCart $cart): array
  208.     {
  209.         $states = [];
  210.         $swStates = (string) $request->cookies->get(self::SYSTEM_STATE_COOKIE);
  211.         if ($swStates !== '') {
  212.             $states array_flip(explode(','$swStates));
  213.         }
  214.         $states $this->switchState($statesself::STATE_LOGGED_IN$context->getCustomer() !== null);
  215.         $states $this->switchState($statesself::STATE_CART_FILLED$cart->getLineItems()->count() > 0);
  216.         return array_keys($states);
  217.     }
  218.     /**
  219.      * @param array<string, int|bool> $states
  220.      *
  221.      * @return array<string, int|bool>
  222.      */
  223.     private function switchState(array $statesstring $keybool $match): array
  224.     {
  225.         if ($match) {
  226.             $states[$key] = true;
  227.             return $states;
  228.         }
  229.         unset($states[$key]);
  230.         return $states;
  231.     }
  232.     private function setCurrencyCookie(Request $requestResponse $response): void
  233.     {
  234.         $currencyId $request->get(SalesChannelContextService::CURRENCY_ID);
  235.         if (!$currencyId) {
  236.             return;
  237.         }
  238.         $cookie Cookie::create(self::CURRENCY_COOKIE$currencyId);
  239.         $cookie->setSecureDefault($request->isSecure());
  240.         $response->headers->setCookie($cookie);
  241.     }
  242. }