Search code examples
shopwareshopware6

How to add additional cache-states for HttpCache in Shopware 6?


I need to distinguish further regarding cache-states for the http-cache. There are two additional parameters, that I want to take into account when caching the response with the HttpCache:

  • The value of the Cloudflare header "cf-ipcountry" in the request
  • the value of an additional cookie that can be set during the request, lets call it "example-cookie"

How can this be achieved?


Solution

  • I think I found the answer: there is \Shopware\Storefront\Framework\Cache\Event\HttpCacheGenerateKeyEvent which is dispatched during the build of the cache-hash (which is used to look up if there is already a cached response or not).

    By creating a subscriber to this event you can modify the cache hash taking your own parameters into regard. So for my example, it would look like something like this:

    class CacheKeySubscriber implements EventSubscriberInterface
    {
    
        public static function getSubscribedEvents(): array
        {
            return [
                HttpCacheGenerateKeyEvent::class => 'onGenerateCacheKey',
            ];
        }
    
        public function onGenerateCacheKey(HttpCacheGenerateKeyEvent $event): void
        {
            $request = $event->getRequest();
            $originalHash = $event->getHash();
    
            $countryHeaderValue = $request->headers->get('cf-ipcountry');
            $exampleCookieValue = $request->cookies->get('example-cookie');
    
            $dataToHash = '';
            if ($countryHeaderValue) {
                $dataToHash .= '-country:' . $countryHeaderValue;
            }
            if ($exampleCookieValue) {
                $dataToHash .= '-exampleCookieValue:' . $exampleCookieValue;
            }
    
            $newHash = hash('sha256', $originalHash . $dataToHash);
            $event->setHash($newHash);
        }
    }