src/Form/EventSubscriber/CustomerRegistrationFormSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventSubscriber;
  3. use Monofony\Contracts\Core\Model\Customer\CustomerInterface;
  4. use Sylius\Component\Resource\Repository\RepositoryInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  7. use Symfony\Component\Form\FormEvent;
  8. use Symfony\Component\Form\FormEvents;
  9. final class CustomerRegistrationFormSubscriber implements EventSubscriberInterface
  10. {
  11.     private $customerRepository;
  12.     public function __construct(RepositoryInterface $customerRepository)
  13.     {
  14.         $this->customerRepository $customerRepository;
  15.     }
  16.     /**
  17.      * {@inheritdoc}
  18.      */
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             FormEvents::PRE_SUBMIT => 'preSubmit',
  23.         ];
  24.     }
  25.     /**
  26.      * {@inheritdoc}
  27.      */
  28.     public function preSubmit(FormEvent $event): void
  29.     {
  30.         $rawData $event->getData();
  31.         $form $event->getForm();
  32.         $data $form->getData();
  33.         if (!$data instanceof CustomerInterface) {
  34.             throw new UnexpectedTypeException($dataCustomerInterface::class);
  35.         }
  36.         // if email is not filled in, go on
  37.         if (!isset($rawData['email']) || empty($rawData['email'])) {
  38.             return;
  39.         }
  40.         $existingCustomer $this->customerRepository->findOneBy(['email' => $rawData['email']]);
  41.         if (null === $existingCustomer || null !== $existingCustomer->getUser()) {
  42.             return;
  43.         }
  44.         $existingCustomer->setUser($data->getUser());
  45.         $form->setData($existingCustomer);
  46.     }
  47. }