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

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