<?php
declare(strict_types=1);
namespace App\EventSubscriber\Auth;
use App\Entity\App\User;
use App\Event\Auth\UserCreatedEvent;
use App\Event\Auth\UserResetEvent;
use App\Service\NotifierInterface;
use DateTime;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserSubscriber implements EventSubscriberInterface
{
protected UserPasswordHasherInterface $encoder;
public function __construct(UserPasswordHasherInterface $passwordEncoder)
{
$this->encoder = $passwordEncoder;
}
public static function getSubscribedEvents(): array
{
return [
UserCreatedEvent::class => ['onUserCreated', 100],
UserResetEvent::class => ['onUserReset', 100],
];
}
public function onUserCreated(UserCreatedEvent $event): void
{
$this->updatePassword($event->getUser());
$this->sendConfirmationEmail($event->getUser(), $event->getNotifier());
}
public function onUserReset(UserResetEvent $event): void
{
$this->sendResetEmail($event->getUser(), $event->getNotifier());
}
/**
* Hash user password
*/
protected function updatePassword(User $user): void
{
$plainPassword = $user->getPlainPassword();
if (!$plainPassword) {
return;
}
$user->setPassword(
$this->encoder->hashPassword($user, $plainPassword)
);
}
/**
* Send email to user email address for account verification
*/
protected function sendConfirmationEmail(User $user, NotifierInterface $notifier): void
{
$notifier->send(
$user->setConfirmationToken(
md5(
microtime()
)
)
);
}
/**
* Send email to user email for password reset
*/
protected function sendResetEmail(User $user, NotifierInterface $notifier): void
{
$notifier->send(
$user->setConfirmationToken(md5(microtime()))
->setPasswordRequestedAt(new DateTime())
);
}
}