<?php
namespace B2bSellersCore\Components\CustomerPrice\Subscriber;
use Shopware\Core\Content\Category\Event\CategoryRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\CrossSellingRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductDetailRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductListingRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductSearchRouteCacheKeyEvent;
use Shopware\Core\Content\Product\Events\ProductSuggestRouteCacheKeyEvent;
use Shopware\Core\Framework\Adapter\Cache\StoreApiRouteCacheKeyEvent;
use Shopware\Core\PlatformRequest;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CacheKeyEventSubscriber implements EventSubscriberInterface
{
private SystemConfigService $configService;
public function __construct(
SystemConfigService $configService
)
{
$this->configService = $configService;
}
public static function getSubscribedEvents(): array
{
return [
CategoryRouteCacheKeyEvent::class => ['disableCache', 100],
ProductDetailRouteCacheKeyEvent::class => ['disableCache', 100],
ProductSuggestRouteCacheKeyEvent::class => ['disableCache', 100],
ProductListingRouteCacheKeyEvent::class => ['disableCache', 100],
ProductSearchRouteCacheKeyEvent::class => ['disableCache', 100],
CrossSellingRouteCacheKeyEvent::class => ['disableCache', 100]
];
}
public function disableCache(StoreApiRouteCacheKeyEvent $event): void
{
$context = $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
if (!$context instanceof SalesChannelContext) {
return;
}
if($this->configService->getBool('B2bSellersCore.config.enableCustomerSpecificCaching', $event->getSalesChannelId())) {
$event->addPart($this->getCustomerHash($context));
return;
}
$event->disableCaching();
}
public function getCustomerHash(SalesChannelContext $context): string
{
return md5((string)json_encode([
$context->getCustomerId(),
$context->getTaxState()
], JSON_THROW_ON_ERROR));
}
}