<?php
namespace Proclane\WegmannTheme\Subscriber;
use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Validation\DataBag\DataBag;
use Shopware\Core\System\SalesChannel\SalesChannel\SalesChannelContextSwitcher;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerLoginSubscriber implements EventSubscriberInterface
{
private const CUSTOM_ZLOTY = 'PLN';
private const ZLOTY_ISO_CODE = 'PLN';
public function __construct(
private readonly SalesChannelContextSwitcher $contextSwitcher,
private readonly EntityRepositoryInterface $currencyRepository,
) {
}
public static function getSubscribedEvents(): array
{
return [
CustomerLoginEvent::class => 'onCustomerLoginEvent'
];
}
public function onCustomerLoginEvent(CustomerLoginEvent $event): void
{
$salesChannelContext = $event->getSalesChannelContext();
/**
* If currency customField is set, retrieve the corresponding currency end update the context.
* If the customField is not set, ignore.
*/
if ($customer_currency = $event->getCustomer()?->getCustomFields()["additional_custom_customer_currency"] ?? null) {
if ($currency_id = $this->getCurrencyId($customer_currency, $salesChannelContext)) {
$this->contextSwitcher->update(
new DataBag(["currencyId" => $currency_id]),
$salesChannelContext
);
}
} /**
* If customField is not set and the current currency is not the default, set back to default.
* This happens if the customField was removed by from the customer after login.
*/
elseif ($salesChannelContext->getSalesChannel()->getCurrencyId() !== $event->getContext()->getCurrencyId()) {
if ($currency_id = $this->getCurrencyId($salesChannelContext->getCurrency()->getIsoCode(),
$salesChannelContext)) {
$this->contextSwitcher->update(
new DataBag(["currencyId" => $currency_id]),
$salesChannelContext
);
}
}
}
private function getCurrencyId(string $iso, SalesChannelContext $context): string|null
{
$criteria = new Criteria();
// Using a switch in case more currencies could be added to the list in the future - Easy implementation
switch ($iso) {
case self::CUSTOM_ZLOTY:
$criteria->addFilter(new EqualsFilter('isoCode', self::ZLOTY_ISO_CODE));
break;
default:
// Get default currency (EUR)
return $context->getSalesChannel()->getCurrencyId();
}
return $this->currencyRepository->searchIds($criteria, $context->getContext())->firstId();
}
}