<?phpnamespace App\EventListener;use App\EventListener\EntityManager;use App\EventListener\TokenGenerator;use App\Event\WelcomeEvent;use App\Model\User\User;use App\Service\MailerService;use DateTime;use Doctrine\ORM\EntityManagerInterface;use FOS\UserBundle\Util\TokenGeneratorInterface;use Symfony\Component\EventDispatcher\EventSubscriberInterface;class WelcomeSubscriber implements EventSubscriberInterface{ /** * @var TokenGenerator */ private $tokenGenerator; /** * @var MailerService */ private $mailerService; /** * @var EntityManager */ private $em; /** * @param TokenGenerator $tokenGenerator * @param EntityManager $em */ public function __construct(TokenGeneratorInterface $tokenGenerator, MailerService $mailer, EntityManagerInterface $em) { $this->tokenGenerator = $tokenGenerator; $this->mailerService = $mailer; $this->em = $em; } public static function getSubscribedEvents(): array { return [ WelcomeEvent::USER_CREATION => [ 'onUserCreation' ], WelcomeEvent::USER_CREATED_USER_NOTIFY_AGAIN => [ 'onUserFailsToClickOnPasswordRegistrationLinkInTime' ] ]; } public function onUserFailsToClickOnPasswordRegistrationLinkInTime(WelcomeEvent $event) { $newUser = $event->getUser(); if ($newUser instanceof User) { // Set a new token and reset the password request date at now $newUser->getEntity()->setPasswordRequestedAt(new DateTime()); $newUser->getEntity()->setConfirmationToken($this->tokenGenerator->generateToken()); $this->em->flush(); // Send another mail $this->mailerService->sendNewAccountWelcomingLink($newUser->getEntity(), false); } } public function onUserCreation(WelcomeEvent $event) { $newUser = $event->getUser(); if ($newUser instanceof User) { /** * @var \App\Entity\User $entity */ $entity = $newUser->getEntity(); // Sets a token to the newly created user if (null === $entity->getConfirmationToken()) { $entity->setPasswordRequestedAt(new DateTime()); $entity->setConfirmationToken($this->tokenGenerator->generateToken()); $this->em->flush(); } // Send a mail with instructions to change their password $this->mailerService->sendNewAccountWelcomingLink($entity); $shops = $newUser->getShops(); $salesPersons = []; foreach ($shops as $shop) { $salesPersons += $shop->getAllAssociatedSalesPersons(); } // Send a mail to the salespersons attached to that user through his/her shops $this->mailerService->sendNewAccountNotificationToSalesPersons($entity, $salesPersons); } }}