<?php
namespace Lnb\Shopware6\LnbPartnerAuth\Subscriber;
use Lnb\Shopware6\LnbPartnerAuth\Config\ConfigServiceAdapter;
use Shopware\Core\Framework\Adapter\Cache\CacheStateSubscriber;
use Shopware\Storefront\Framework\Cache\CacheResponseSubscriber;
use Shopware\Storefront\Framework\Cache\Event\HttpCacheHitEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class HttpCacheHitSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly ConfigServiceAdapter $configServiceAdapter
) {
}
public static function getSubscribedEvents(): array
{
return [
HttpCacheHitEvent::class => 'onHttpCacheHit',
];
}
public function onHttpCacheHit(HttpCacheHitEvent $event): void
{
$salesChannelId = $event->getRequest()->attributes->get('sw-sales-channel-id');
$this->configServiceAdapter->setSalesChannelId($salesChannelId);
$partnerSalesChannelId = $this->configServiceAdapter->getPartnerSalesChannelId();
if ($partnerSalesChannelId !== $salesChannelId || $this->isCustomerLoggedIn($this->getSystemStates($event->getRequest()))) {
return;
}
//disable http cache for PartnerSalesChannel when customer is not logged in to always redirect partner pages to login page
$event->getResponse()->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
}
/**
* @return array<string, int>
*/
private function getSystemStates(Request $request): array
{
$states = [];
$swStates = (string) $request->cookies->get(CacheResponseSubscriber::SYSTEM_STATE_COOKIE);
if ($swStates !== '') {
$states = array_flip(explode(',', $swStates));
}
return $states;
}
/**
* @param array<string, int> $systemStates
*/
private function isCustomerLoggedIn(array $systemStates): bool
{
return array_key_exists(CacheStateSubscriber::STATE_LOGGED_IN, $systemStates);
}
}