custom/plugins/sw-asus/src/Subscriber/NewsletterSubscriptionSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace Onedot\Asus\Subscriber;
  3. use Shopware\Core\Checkout\Customer\Event\CustomerRegisterEvent;
  4. use NewsletterSendinblue\Service\Customer\CustomerProducer;
  5. use Shopware\Core\Framework\Context;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Psr\Log\LoggerInterface;
  10. class NewsletterSubscriptionSubscriber implements EventSubscriberInterface
  11. {
  12.     private $logger;
  13.     private $requestStack;
  14.     /**
  15.      * @var CustomerProducer
  16.      */
  17.     private $customerProducer;
  18.     private EntityRepository $newsletterRecipientRepository;
  19.     public function __construct(EntityRepository $newsletterRecipientRepositoryRequestStack $requestStackCustomerProducer $customerProducerLoggerInterface $logger)
  20.     {
  21.         $this->newsletterRecipientRepository $newsletterRecipientRepository;
  22.         $this->customerProducer $customerProducer;
  23.         $this->requestStack $requestStack;
  24.         $this->logger $logger;
  25.     }
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             CustomerRegisterEvent::class => 'onCustomerRegister',
  30.         ];
  31.     }
  32.     public function onCustomerRegister(CustomerRegisterEvent $event): void
  33.     {
  34.         $customer $event->getCustomer();
  35.         $customFields $customer->getCustomFields() ?? [];
  36.         // $this->logger->error("Custom fields", $this->requestStack->getCurrentRequest()->request->all());
  37.         // Check if the newsletter checkbox is selected
  38.         if (!empty($this->requestStack->getCurrentRequest()->request->all()["newsletter_subscribed"] ?? "")) {
  39.             $email $customer->getEmail();
  40.             $salesChannelId $customer->getSalesChannelId();
  41.             $hash bin2hex(random_bytes(16));
  42.             // Prepare the data for the newsletter recipient
  43.             $newsletterData = [
  44.                 'email' => $email,
  45.                 'salutationId' => $customer->getSalutationId(),
  46.                 'firstName' => $customer->getFirstName(),
  47.                 'lastName' => $customer->getLastName(),
  48.                 'salesChannelId' => $salesChannelId,
  49.                 'status' => "optIn",
  50.                 'hash' => $hash,
  51.             ];
  52.             // Save the newsletter subscription
  53.             $this->newsletterRecipientRepository->upsert([$newsletterData], Context::createDefaultContext());
  54.             $this->customerProducer->confirmContact($customer$event->getContext(), $event->getSalesChannelId());
  55.         }
  56.     }
  57. }