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