src/EventSubscriber/SendVerificationEmailEventSubscriber.php line 39
<?php
namespace App\EventSubscriber;
use App\Event\SendEmailEvent;
use App\Event\SendVerificationEmailEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SendVerificationEmailEventSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
private EventDispatcherInterface $eventDispatcher;
private string $fromEmail;
private string $fromName;
public function __construct(EntityManagerInterface $entityManager, EventDispatcherInterface $eventDispatcher,
string $fromEmail, string $fromName)
{
$this->entityManager = $entityManager;
$this->eventDispatcher = $eventDispatcher;
$this->fromEmail = $fromEmail;
$this->fromName = $fromName;
}
public static function getSubscribedEvents(): array
{
return [
SendVerificationEmailEvent::NAME => [
['handleVerificationEmail', 10]
]
];
}
public function handleVerificationEmail(SendVerificationEmailEvent $event): void
{
$user = $event->getUser();
if($event->getAction() == 'register')
{
$user->setEmailOtp($this->generateOtp());
$user->setEmailOtpGeneratedAt(new \DateTimeImmutable('now'));
$otp = $user->getEmailOtp();
}
else {
$user->setResetPasswordOtp($this->generateOtp());
$user->setResetPasswordOtpGeneratedAt(new \DateTimeImmutable('now'));
$otp = $user->getResetPasswordOtp();
}
$this->entityManager->flush();
$emailParameters = [
'from' => [
'email' => $this->fromEmail,
'name' => $this->fromName
],
'to' => [
'email' => $user->getEmail()
],
'subject' => 'Verify your email',
'template' => 'registration/verification_email.html.twig',
'parameters' => [
'emailOtp' => $otp
]
];
$emailEvent = new SendEmailEvent($emailParameters);
$this->eventDispatcher->dispatch($emailEvent, SendEmailEvent::NAME);
}
public function generateOtp(): string
{
$length = 6; $chars = '1234567890';
$chars_length = (strlen($chars) - 1);
$string = $chars[rand(0, $chars_length)];
for ($i = 1; $i < $length; $i = strlen($string)) {
$r = $chars[rand(0, $chars_length)];
if ($r != $string[$i - 1])
$string .= $r;
}
return $string;
}
}