<?php declare(strict_types=1);
namespace Acris\CheckoutMethodPreselect\Storefront\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Validation\DataBag\DataBag;
use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService;
use Shopware\Core\System\SalesChannel\Event\SalesChannelContextRestoredEvent;
use Shopware\Core\System\SalesChannel\SalesChannel\SalesChannelContextSwitcher;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LoginPaymentMethodSubscriber implements EventSubscriberInterface
{
private SystemConfigService $configService;
private SalesChannelContextSwitcher $salesChannelContextSwitcher;
public function __construct(
SystemConfigService $configService,
SalesChannelContextSwitcher $salesChannelContextSwitcher
) {
$this->configService = $configService;
$this->salesChannelContextSwitcher = $salesChannelContextSwitcher;
}
public static function getSubscribedEvents(): array
{
return [
SalesChannelContextRestoredEvent::class => 'onSalesChannelContextRestoredEvent'
];
}
public function onSalesChannelContextRestoredEvent(SalesChannelContextRestoredEvent $event)
{
if($this->configService->get('AcrisCheckoutMethodPreselectCS.config.overruleCustomerAssignedPaymentMethod', $event->getRestoredSalesChannelContext()->getSalesChannelId()) === 'ignore') {
if($event->getCurrentSalesChannelContext() instanceof SalesChannelContext && $event->getRestoredSalesChannelContext()->getCustomer() instanceof CustomerEntity
&& $event->getRestoredSalesChannelContext()->getPaymentMethod()->getId() !== $event->getCurrentSalesChannelContext()->getPaymentMethod()->getId()
) {
$this->salesChannelContextSwitcher->update(new DataBag([SalesChannelContextService::PAYMENT_METHOD_ID => $event->getCurrentSalesChannelContext()->getPaymentMethod()->getId()]), $event->getRestoredSalesChannelContext());
}
}
}
}