vendor/shopware/platform/src/Storefront/Framework/Cache/CacheResponseSubscriber.php line 60

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