custom/plugins/FourtwosixRegistrationFields/src/Subscriber/ItalyCountryIdSubscriber.php line 37

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace FourtwosixRegistrationFields\Subscriber;
  4. use Shopware\Core\Framework\Context;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  8. use Shopware\Core\System\Country\CountryEntity;
  9. use Shopware\Core\System\Salutation\SalutationEntity;
  10. use Shopware\Storefront\Page\Account\Login\AccountLoginPageLoadedEvent;
  11. use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
  12. use Shopware\Storefront\Page\GenericPageLoadedEvent;
  13. use Shopware\Storefront\Page\PageLoadedEvent;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. class ItalyCountryIdSubscriber implements EventSubscriberInterface
  16. {
  17.     private EntityRepository $countryRepository;
  18.     public function __construct(
  19.         EntityRepository $countryRepository,
  20.         private readonly EntityRepository $salutationRepository,
  21.     ) {
  22.         $this->countryRepository $countryRepository;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             GenericPageLoadedEvent::class => 'onItalyCountryId',
  28.         ];
  29.     }
  30.     public function onItalyCountryId(PageLoadedEvent $event): void
  31.     {
  32.         $context $event->getContext();
  33.         if (empty($italy $this->getCountryFromISO($context'IT'))) {
  34.             return;
  35.         }
  36.         $salutation $this->getDefaultSalutation($context);
  37.         if (empty($salutation)) {
  38.             return;
  39.         }
  40.         $countryId $italy->getId();
  41.         $salutationId $salutation->getId();
  42.         $extensions $event->getPage()->getExtensions();
  43.         $extensions['italyCountryId'] = $countryId;
  44.         $extensions['salutationId'] = $salutationId;
  45.         $event->getPage()->setExtensions($extensions);
  46.     }
  47.     private function getCountryFromISO(Context $contextstring $iso): CountryEntity
  48.     {
  49.         $criteria = new Criteria();
  50.         $criteria->addFilter(new EqualsFilter('iso'$iso));
  51.         return $this->countryRepository->search($criteria$context)->first();
  52.     }
  53.     private function getDefaultSalutation(Context $context): ?SalutationEntity
  54.     {
  55.         $criteria = new Criteria();
  56.         $criteria->addFilter(new EqualsFilter('salutationKey''not_specified'));
  57.         return $this->salutationRepository->search($criteria$context)->first();
  58.     }
  59. }