src/Form/EventSubscriber/AddUserFormSubscriber.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventSubscriber;
  3. use App\Entity\Customer\Customer;
  4. use App\Form\Type\User\AppUserType;
  5. use Sylius\Component\User\Model\UserAwareInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  8. use Symfony\Component\Form\FormEvent;
  9. use Symfony\Component\Form\FormEvents;
  10. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  11. use Symfony\Component\Validator\Constraints\Valid;
  12. use Webmozart\Assert\Assert;
  13. final class AddUserFormSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var UserPasswordEncoderInterface
  17.      */
  18.     private $passwordEncoder;
  19.     public function __construct(UserPasswordEncoderInterface $passwordEncoder)
  20.     {
  21.         $this->passwordEncoder $passwordEncoder;
  22.     }
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [
  26.             FormEvents::PRE_SET_DATA => 'preSetData',
  27.             FormEvents::SUBMIT => 'submit',
  28.         ];
  29.     }
  30.     /**
  31.      */
  32.     public function preSetData(FormEvent $event): void
  33.     {
  34.         $form $event->getForm();
  35.         $form->add('user'AppUserType::class, ['constraints' => [new Valid()]]);
  36.         $form->add('createUser'CheckboxType::class, [
  37.             'label' => 'app.ui.create_user',
  38.             'required' => false,
  39.             'mapped' => false,
  40.         ]);
  41.     }
  42.     /**
  43.      * @param FormEvent $event
  44.      */
  45.     public function submit(FormEvent $event): void
  46.     {
  47.         $data $event->getData();
  48.         $form $event->getForm();
  49.         /* @var UserAwareInterface $data */
  50.         Assert::isInstanceOf($dataCustomer::class);
  51.         $data->setUsername($data->getEmail());
  52.         if (null === $data->getUser()->getId() && null === $form->get('createUser')->getViewData()) {
  53.             $password $this->passwordEncoder->encodePassword($data->getUser(), $data->getUser()->getPlainPassword());
  54.             $data->setPassword($password);
  55.             $data->setUsername($data->getEmail());
  56.             $data->setUser(null);
  57.             $event->setData($data);
  58.             $form->remove('user');
  59.             $form->add('user'AppUserType::class, ['constraints' => [new Valid()]]);
  60.         }
  61.     }
  62. }