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

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\PlatformRequest;
  6. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService;
  7. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  8. use Shopware\Storefront\Framework\Cache\Annotation\HttpCache;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Cookie;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. class CacheResponseSubscriber implements EventSubscriberInterface
  16. {
  17.     public const STATE_LOGGED_IN 'logged-in';
  18.     public const STATE_CART_FILLED 'cart-filled';
  19.     public const CURRENCY_COOKIE 'sw-currency';
  20.     public const CONTEXT_CACHE_COOKIE 'sw-cache-hash';
  21.     public const SYSTEM_STATE_COOKIE 'sw-states';
  22.     public const INVALIDATION_STATES_HEADER 'sw-invalidation-states';
  23.     /**
  24.      * @var CartService
  25.      */
  26.     private $cartService;
  27.     /**
  28.      * @var int
  29.      */
  30.     private $defaultTtl;
  31.     public function __construct(CartService $cartServiceint $defaultTtl)
  32.     {
  33.         $this->cartService $cartService;
  34.         $this->defaultTtl $defaultTtl;
  35.     }
  36.     public static function getSubscribedEvents()
  37.     {
  38.         return [
  39.             KernelEvents::RESPONSE => [
  40.                 ['setResponseCache', -1500],
  41.             ],
  42.         ];
  43.     }
  44.     public function setResponseCache(ResponseEvent $event): void
  45.     {
  46.         $response $event->getResponse();
  47.         $request $event->getRequest();
  48.         $context $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  49.         if (!$context instanceof SalesChannelContext) {
  50.             return;
  51.         }
  52.         $route $request->attributes->get('_route');
  53.         if ($route === 'frontend.checkout.configure') {
  54.             $this->setCurrencyCookie($request$response);
  55.         }
  56.         /* @var SalesChannelContext $context */
  57.         $states $this->updateSystemState($context$request$response);
  58.         if ($request->getMethod() !== Request::METHOD_GET) {
  59.             return;
  60.         }
  61.         if ($context->getCustomer()) {
  62.             $response->headers->setCookie(Cookie::create(self::CONTEXT_CACHE_COOKIE$this->buildCacheHash($context)));
  63.         } else {
  64.             $response->headers->removeCookie(self::CONTEXT_CACHE_COOKIE);
  65.             $response->headers->clearCookie(self::CONTEXT_CACHE_COOKIE);
  66.         }
  67.         $config $request->attributes->get('_' HttpCache::ALIAS);
  68.         if (empty($config)) {
  69.             return;
  70.         }
  71.         /** @var HttpCache $cache */
  72.         $cache array_shift($config);
  73.         if ($this->hasInvalidationState($cache$states)) {
  74.             return;
  75.         }
  76.         $maxAge $cache->getMaxAge() ?? $this->defaultTtl;
  77.         $maxAge $maxAge ?? 3600;
  78.         $response->setSharedMaxAge($maxAge);
  79.         $response->headers->addCacheControlDirective('must-revalidate');
  80.         $response->headers->set(
  81.             self::INVALIDATION_STATES_HEADER,
  82.             implode(','$cache->getStates())
  83.         );
  84.     }
  85.     private function hasInvalidationState(HttpCache $cache, array $states): bool
  86.     {
  87.         foreach ($states as $state) {
  88.             if (in_array($state$cache->getStates(), true)) {
  89.                 return true;
  90.             }
  91.         }
  92.         return false;
  93.     }
  94.     private function buildCacheHash(SalesChannelContext $context): string
  95.     {
  96.         return md5(json_encode([
  97.             $context->getRuleIds(),
  98.             $context->getContext()->getVersionId(),
  99.             $context->getCurrency()->getId(),
  100.         ]));
  101.     }
  102.     /**
  103.      * System states can be used to stop caching routes at certain states. For example,
  104.      * the checkout routes are no longer cached if the customer has products in the cart or is logged in.
  105.      */
  106.     private function updateSystemState(SalesChannelContext $contextRequest $requestResponse $response): array
  107.     {
  108.         $cart $this->cartService->getCart($context->getToken(), $context);
  109.         $states $this->getSystemStates($request$context$cart);
  110.         if (empty($states)) {
  111.             $response->headers->removeCookie(self::SYSTEM_STATE_COOKIE);
  112.             $response->headers->clearCookie(self::SYSTEM_STATE_COOKIE);
  113.             return [];
  114.         }
  115.         $response->headers->setCookie(
  116.             Cookie::create(self::SYSTEM_STATE_COOKIEimplode(','$states))
  117.         );
  118.         return $states;
  119.     }
  120.     private function getSystemStates(Request $requestSalesChannelContext $contextCart $cart): array
  121.     {
  122.         $states = [];
  123.         if ($request->cookies->has(self::SYSTEM_STATE_COOKIE)) {
  124.             $states explode(','$request->cookies->get(self::SYSTEM_STATE_COOKIE));
  125.             $states array_flip($states);
  126.         }
  127.         $states $this->switchState($statesself::STATE_LOGGED_IN$context->getCustomer() !== null);
  128.         $states $this->switchState($statesself::STATE_CART_FILLED$cart->getLineItems()->count() > 0);
  129.         return array_keys($states);
  130.     }
  131.     private function switchState(array $statesstring $keybool $match): array
  132.     {
  133.         if ($match) {
  134.             $states[$key] = true;
  135.             return $states;
  136.         }
  137.         unset($states[$key]);
  138.         return $states;
  139.     }
  140.     private function setCurrencyCookie(Request $requestResponse $response): void
  141.     {
  142.         $currencyId $request->get(SalesChannelContextService::CURRENCY_ID);
  143.         if (!$currencyId) {
  144.             return;
  145.         }
  146.         $response->headers->setCookie(Cookie::create(self::CURRENCY_COOKIE$currencyId));
  147.     }
  148. }