<?php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Events;
use App\Mailer\UserMailer;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
class SecuritySubscriber implements EventSubscriberInterface
{
protected $objectManager;
protected $tokenGenerator;
protected $userMailer;
public function __construct(
ObjectManager $objectManager,
TokenGeneratorInterface $tokenGenerator,
UserMailer $userMailer
) {
$this->objectManager = $objectManager;
$this->tokenGenerator = $tokenGenerator;
$this->userMailer = $userMailer;
}
public static function getSubscribedEvents(): array
{
return [
Events::PASSWORD_RESET => 'onPasswordReset'
];
}
public function onPasswordReset(GenericEvent $event): void
{
/** @var User $user */
$user = $event->getSubject();
$this->sendPasswordResetMessage($user);
}
/**
* Sends password reset message to the User's email address.
*
* @param User $user
*
* @return User
*/
private function sendPasswordResetMessage(User $user)
{
//Just to get rid of throwing null token value validation error when generating the reset password link.
if (!$user->getConfirmationToken()) {
$this->generateRegistrationConfirmationToken($user);
}
$this->userMailer->sendResettingEmailMessage($user);
return $user;
}
/**
* Generates a new registration confirmation token for the given User and persists the entity.
*
* @param User $user
*
* @return User
*/
private function generateRegistrationConfirmationToken($user)
{
$token = $this->tokenGenerator->generateToken();
$user->setConfirmationToken($token);
$this->objectManager->persist($user);
$this->objectManager->flush();
return $user;
}
}