src/EventSubscriber/UserRegistrationSubscriber.php line 42

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