<?php
namespace App\EventSubscriber\User;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\UserInterface;
final class UserEncodePasswordSubscriber implements EventSubscriberInterface
{
private UserPasswordHasherInterface $passwordEncoder;
public function __construct(UserPasswordHasherInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['encodePassword', EventPriorities::PRE_WRITE],
];
}
public function encodePassword(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$user instanceof UserInterface || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
if (!$user instanceof User || !$user->getPlainPassword()) {
return;
}
$user->setPassword(
$this->passwordEncoder->hashPassword(
$user,
$user->getPlainPassword()
)
);
$user->eraseCredentials();
}
}