<?php
namespace Boldr\Cms\UsersBundle\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Boldr\Cms\UsersBundle\EmailFactory;
use Boldr\Cms\UsersBundle\Event\UserCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\MailerInterface;
class UserEventSubscriber implements EventSubscriberInterface
{
private MailerInterface $mailer;
private EmailFactory $emailFactory;
private EntityManagerInterface $em;
public function __construct(
MailerInterface $mailer,
EmailFactory $emailFactory,
EntityManagerInterface $em
)
{
$this->mailer = $mailer;
$this->emailFactory = $emailFactory;
$this->em = $em;
}
public static function getSubscribedEvents(): array
{
return [
UserCreatedEvent::class => [
['onUserCreated', 10]
]
];
}
public function onUserCreated(UserCreatedEvent $event)
{
$user = $event->getUser();
$confirmEmailAddressToken = bin2hex(random_bytes(32));
$user->setConfirmEmailAddressToken($confirmEmailAddressToken);
$this->em->flush();
if ($event->getSendWelcomeEmail())
{
// try
// {
$this->mailer->send($this->emailFactory->createWelcomeEmail($user));
// }
// catch (\Exception $ex)
// {
// could not send email
// }
}
}
}