src/EventSubscriber/UserRegistrationSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use Monofony\Contracts\Core\Model\Customer\CustomerInterface;
  5. use Doctrine\Persistence\ObjectManager;
  6. use Sylius\Bundle\UserBundle\UserEvents;
  7. use Sylius\Component\User\Model\UserInterface;
  8. use Sylius\Component\User\Security\Generator\GeneratorInterface;
  9. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\EventDispatcher\GenericEvent;
  12. use Webmozart\Assert\Assert;
  13. final class UserRegistrationSubscriber implements EventSubscriberInterface
  14. {
  15.     private $userManager;
  16.     private $tokenGenerator;
  17.     private $eventDispatcher;
  18.     public function __construct(
  19.         ObjectManager $userManager,
  20.         GeneratorInterface $tokenGenerator,
  21.         EventDispatcherInterface $eventDispatcher
  22.     ) {
  23.         $this->userManager $userManager;
  24.         $this->tokenGenerator $tokenGenerator;
  25.         $this->eventDispatcher $eventDispatcher;
  26.     }
  27.     /**
  28.      * {@inheritdoc}
  29.      */
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.             'sylius.customer.post_register' => 'handleUserVerification',
  34.         ];
  35.     }
  36.     public function handleUserVerification(GenericEvent $event): void
  37.     {
  38.         $customer $event->getSubject();
  39.         Assert::isInstanceOf($customerCustomerInterface::class);
  40.         $user $customer->getUser();
  41.         Assert::notNull($user);
  42.         $this->sendVerificationEmail($user);
  43.     }
  44.     private function sendVerificationEmail(UserInterface $user): void
  45.     {
  46.         $token $this->tokenGenerator->generate();
  47.         $user->setEmailVerificationToken($token);
  48.         $this->userManager->persist($user);
  49.         $this->userManager->flush();
  50.         $this->eventDispatcher->dispatch(new GenericEvent($user), UserEvents::REQUEST_VERIFICATION_TOKEN);
  51.     }
  52. }