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

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