<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserSubscriber implements EventSubscriberInterface
{
public function __construct(
protected UserPasswordHasherInterface $passwordHasher
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['setPassword', EventPriorities::PRE_VALIDATE],
],
];
}
public function setPassword(ViewEvent $event): void
{
$user = $event->getControllerResult();
if ($user instanceof User && $user->getPlainPassword()) {
$plaintextPassword = $user->getPlainPassword();
$hashedPassword = $this->passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
$user->setPlainPassword(null);
}
}
}