src/EventSubscriber/User/UserEncodePasswordSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\User;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. final class UserEncodePasswordSubscriber implements EventSubscriberInterface
  12. {
  13.     private UserPasswordHasherInterface $passwordEncoder;
  14.     public function __construct(UserPasswordHasherInterface $passwordEncoder)
  15.     {
  16.         $this->passwordEncoder $passwordEncoder;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             KernelEvents::VIEW => ['encodePassword'EventPriorities::PRE_WRITE],
  22.         ];
  23.     }
  24.     public function encodePassword(ViewEvent $event): void
  25.     {
  26.         $user $event->getControllerResult();
  27.         $method $event->getRequest()->getMethod();
  28.         if (!$user instanceof UserInterface || !in_array($method, [Request::METHOD_POSTRequest::METHOD_PUT])) {
  29.             return;
  30.         }
  31.         if (!$user instanceof User || !$user->getPlainPassword()) {
  32.             return;
  33.         }
  34.         $user->setPassword(
  35.             $this->passwordEncoder->hashPassword(
  36.                 $user,
  37.                 $user->getPlainPassword()
  38.             )
  39.         );
  40.         $user->eraseCredentials();
  41.     }
  42. }