<?php declare(strict_types=1); 
 
namespace Dvdw\PlatformChoice\Framework\Cache; 
 
use Dvdw\PlatformChoice\Framework\Routing\RequestValidator; 
use Dvdw\PlatformChoice\System\SalesChannel\Struct\PlatformChoiceExtension; 
use Shopware\Core\PlatformRequest; 
use Shopware\Core\System\SalesChannel\SalesChannelContext; 
use Shopware\Storefront\Framework\Cache\Event\HttpCacheGenerateKeyEvent; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
 
class HttpCacheKeySubscriber implements EventSubscriberInterface 
{ 
    private RequestValidator $requestValidator; 
 
    private CrawlerDetector $crawlerDetector; 
 
    public function __construct( 
        RequestValidator $requestValidator, 
        CrawlerDetector  $crawlerDetector 
    ) 
    { 
        $this->requestValidator = $requestValidator; 
        $this->crawlerDetector = $crawlerDetector; 
    } 
     
    public static function getSubscribedEvents(): iterable 
    { 
        return [HttpCacheGenerateKeyEvent::class => 'extendKey']; 
    } 
 
    public function extendKey(HttpCacheGenerateKeyEvent $event): void 
    { 
        $request = $event->getRequest(); 
 
        if (!$this->requestValidator->isNormalStorefrontRequest($request)) { 
            return; 
        } 
 
        $hash = $event->getHash(); 
        $suffix = PlatformChoiceExtension::B2C; 
 
        if ($request->cookies->has(PlatformChoiceExtension::KEY)) { 
            $suffix = $request->cookies->get(PlatformChoiceExtension::KEY); 
        } 
 
        /**@var SalesChannelContext|null $context */ 
        $context = $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT); 
 
        if ($context !== null) { 
            /** @var PlatformChoiceExtension|null $extension */ 
            $extension = $context->getExtension(PlatformChoiceExtension::KEY); 
 
            if ($extension !== null) { 
                $suffix = $extension->getChoice(); 
            } 
        } 
 
        if ($this->crawlerDetector->isCrawler($request)) { 
            $suffix = Crawler::IS_CRAWLER; 
        } 
 
        $event->setHash(hash('sha256', $hash . '-' . $suffix)); 
    } 
}