<?php
declare(strict_types=1);
namespace FourtwosixRegistrationFields\Subscriber;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\Country\CountryEntity;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ItalyCountryIdSubscriber implements EventSubscriberInterface
{
private EntityRepository $countryRepository;
public function __construct(
EntityRepository $countryRepository
) {
$this->countryRepository = $countryRepository;
}
public static function getSubscribedEvents(): array
{
return [
GenericPageLoadedEvent::class => 'onItalyCountryId',
];
}
public function onItalyCountryId(PageLoadedEvent $event): void
{
$context = $event->getContext();
if (empty($italy = $this->getCountryFromISO($context, 'IT'))) {
return;
}
$countryId = $italy->getId();
$extensions = $event->getPage()->getExtensions();
$extensions['italyCountryId'] = $countryId;
$event->getPage()->setExtensions($extensions);
}
private function getCountryFromISO(Context &$context, string $iso): CountryEntity
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('iso', $iso));
return $this->countryRepository->search($criteria, $context)->first();
}
}