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

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