custom/plugins/HemoCustomerGroupRestriction/src/Subscriber/HttpCacheCustomerGroupSubscriber.php line 30

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Hemo\CustomerGroupRestriction\Subscriber;
  3. use Shopware\Core\PlatformRequest;
  4. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  5. use Shopware\Storefront\Framework\Cache\Event\HttpCacheGenerateKeyEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Cookie;
  8. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. /**
  11.  * The storefront HTTP cache key only contains rule ids, currency, version and the logged-in
  12.  * state. Two logged-in customers from different customer groups would therefore share cached
  13.  * pages. This subscriber stores the customer group in a cookie and mixes it into the cache key.
  14.  */
  15. final class HttpCacheCustomerGroupSubscriber implements EventSubscriberInterface
  16. {
  17.     public const COOKIE_NAME 'hemo-customer-group';
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::RESPONSE => 'onResponse',
  22.             HttpCacheGenerateKeyEvent::class => 'onGenerateKey',
  23.         ];
  24.     }
  25.     public function onResponse(ResponseEvent $event): void
  26.     {
  27.         if (!$event->isMainRequest()) {
  28.             return;
  29.         }
  30.         $request $event->getRequest();
  31.         $scopes $request->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  32.         if (!\is_array($scopes) || !\in_array('storefront'$scopestrue)) {
  33.             return;
  34.         }
  35.         $context $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  36.         if (!$context instanceof SalesChannelContext) {
  37.             return;
  38.         }
  39.         $customerGroupId $context->getCurrentCustomerGroup()->getId();
  40.         if ($request->cookies->get(self::COOKIE_NAME) === $customerGroupId) {
  41.             return;
  42.         }
  43.         $cookie Cookie::create(self::COOKIE_NAME$customerGroupId);
  44.         $cookie->setSecureDefault($request->isSecure());
  45.         $event->getResponse()->headers->setCookie($cookie);
  46.     }
  47.     public function onGenerateKey(HttpCacheGenerateKeyEvent $event): void
  48.     {
  49.         $customerGroupId $event->getRequest()->cookies->get(self::COOKIE_NAME);
  50.         if (!\is_string($customerGroupId) || $customerGroupId === '') {
  51.             return;
  52.         }
  53.         $event->setHash(hash('sha256'$event->getHash() . '-' $customerGroupId));
  54.     }
  55. }