<?php
declare(strict_types=1);
namespace NetInventors\NetiNextAccessManager\Subscriber;
use NetInventors\NetiNextAccessManager\Constants\ConfigConstants;
use NetInventors\NetiNextAccessManager\Service\PluginConfig;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Content\Category\Event\CategoryRouteCacheKeyEvent;
use Shopware\Core\Content\LandingPage\Event\LandingPageRouteCacheKeyEvent;
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 Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
class Cache implements EventSubscriberInterface
{
private PluginConfig $pluginConfig;
public function __construct(PluginConfig $pluginConfig)
{
$this->pluginConfig = $pluginConfig;
}
public static function getSubscribedEvents(): array
{
return [
ProductDetailRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
ProductListingRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
ProductSearchRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
ProductSuggestRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
CategoryRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
CrossSellingRouteCacheKeyEvent::class => [ [ 'onCacheKeyEvent' ], [ 'storeRoute' ] ],
LandingPageRouteCacheKeyEvent::class => 'storeRoute',
];
}
/**
* @throws \Exception
*/
public function onCacheKeyEvent(StoreApiRouteCacheKeyEvent $event): void
{
$customer = $event->getContext()->getCustomer();
$loginState = (int) ($customer instanceof CustomerEntity);
$event->addPart('neti-access-manager-login-state-' . $loginState);
}
public function storeRoute(StoreApiRouteCacheKeyEvent $event): void
{
$request = $event->getRequest();
if (
!$this->pluginConfig->isActive()
|| !is_string($request->attributes->get('sw-sales-channel-id'))
|| $event->getContext()->getCustomer() instanceof CustomerEntity
) {
return;
}
try {
$session = $request->getSession();
} catch (SessionNotFoundException $ex) {
return;
}
if (
$this->pluginConfig->getLoginRedirectType() === ConfigConstants::CONFIG_REDIRECT_TYPE_REFERER
&& $request->isXmlHttpRequest() === false
) {
$referer = [
'route' => (string) $request->attributes->get('_route'),
'routeParams' => (array) $request->attributes->get('_route_params'),
];
if (
!\in_array($referer['route'], [
'frontend.account.login.page',
'frontend.account.logout.page',
'frontend.checkout.info',
'api.customer.update'
])
) {
$session->set('neti-access-manager-referer', $referer);
}
}
}
}