<?php
namespace Lnb\Shopware6\LnbPartnerAuth\Subscriber;
use Lnb\Shopware6\LnbPartnerAuth\Config\ConfigServiceAdapter;
use Lnb\Shopware6\LnbPartnerAuth\Service\PartnerSessionResolver;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
class SalesChannelResolvedSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly RequestStack $requestStack,
private readonly PartnerSessionResolver $partnerSessionResolver,
private readonly ConfigServiceAdapter $configServiceAdapter
) {
}
public static function getSubscribedEvents(): array
{
return [
SalesChannelContextResolvedEvent::class => 'onSalesChannelResolved',
];
}
public function onSalesChannelResolved(SalesChannelContextResolvedEvent $event): void
{
$this->configServiceAdapter->setSalesChannelId($event->getSalesChannelContext()->getSalesChannelId());
$partnerSalesChannelId = $this->configServiceAdapter->getPartnerSalesChannelId();
$salesChannelId = $event->getSalesChannelContext()->getSalesChannelId();
if ($partnerSalesChannelId !== $salesChannelId) {
return; //wrong sales channel
}
$request = $this->requestStack->getCurrentRequest();
if ($request === null) {
return; // no request probably cli context
}
if ($request->attributes->get('_route') === 'frontend.account.recover.page') {
//link to password recover page
$redirect = $this->configServiceAdapter->getPartnerPasswordRecoverUrl();
$redirect .= substr($redirect, -1) === '/' ? '' : '/';
(new RedirectResponse($redirect))->send();
}
if ($event->getSalesChannelContext()->getCustomer() instanceof CustomerEntity) {
return; //customer logged in
}
$this->partnerSessionResolver->resolve($request, $event->getSalesChannelContext());
}
}