<?php
namespace App\EventSubscriber\Security;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User\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;
final class UserPasswordEncoder implements EventSubscriberInterface
{
private UserPasswordHasherInterface $passwordEncoder;
public function __construct(UserPasswordHasherInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['encodePassword', EventPriorities::PRE_VALIDATE],
],
];
}
public function encodePassword(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
//only for PUT or POST on User entity
if (!$user instanceof User || !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT])) {
return;
}
// set password with encoded plainPassword if not empty
if( $user->getPlainPassword() ) {
$pass = $this->passwordEncoder->hashPassword($user, $user->getPlainPassword());
$user->setPassword($pass);
}
}
}