<?php
/**
* Created by PhpStorm.
* User: Unknown
* Date: 07/10/2019
* Time: 14:46
*/
namespace App\EventSubscriber;
use App\Email\Mail;
use App\Entity\Event;
use App\Entity\User;
use App\Security\TokenGenerator;
use App\Events;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Validator\Constraints\DateTime;
use Twilio\Exceptions\TwilioException;
class UserRegistrationSubscriber implements EventSubscriberInterface
{
private $tokenGenerator;
private $mailer;
private $entityManager;
public function __construct(TokenGenerator $tokenGenerator,Mail $mailer,EntityManagerInterface $entityManager)
{
$this->tokenGenerator = $tokenGenerator;
$this->mailer = $mailer;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents() : array
{
return [
Events::USER_REGISTERED => 'registrationSuccess',
];
}
/**
* @param GenericEvent $event
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function registrationSuccess(GenericEvent $event): void
{
/** @var User $user */
$user = $event->getSubject();
if (!$user instanceof User){
return;
}
$user
->setConfirmationToken($this->tokenGenerator->getRandomSecureToken())
->setConfirmationTokenSentAt(new \DateTime());
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->mailer->sendConfirmationEmail($user);
if($user->getSmsEnabled() == 1) {
try {
$this->mailer->sendVerificationSms($user);
} catch (TwilioException $e) {
}
}
}
}