src/EventSubscriber/Security/UserPasswordEncoder.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Security;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User\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. final class UserPasswordEncoder implements EventSubscriberInterface
  11. {
  12.     private UserPasswordHasherInterface $passwordEncoder;
  13.     public function __construct(UserPasswordHasherInterface $passwordEncoder)
  14.     {
  15.         $this->passwordEncoder $passwordEncoder;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => [
  21.                 ['encodePassword'EventPriorities::PRE_VALIDATE],
  22.             ],
  23.         ];
  24.     }
  25.     public function encodePassword(ViewEvent $event): void
  26.     {
  27.         $user $event->getControllerResult();
  28.         $method $event->getRequest()->getMethod();
  29.         //only for PUT or POST on User entity
  30.         if (!$user instanceof User || !in_array($method, [Request::METHOD_POSTRequest::METHOD_PUT])) {
  31.             return;
  32.         }
  33.         // set password with encoded plainPassword if not empty
  34.         if( $user->getPlainPassword() ) {
  35.             $pass $this->passwordEncoder->hashPassword($user$user->getPlainPassword());
  36.             $user->setPassword($pass);
  37.         }
  38.     }
  39. }