src/EventSubscriber/UserSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\ViewEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. class UserSubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         protected UserPasswordHasherInterface $passwordHasher
  13.     ) {
  14.     }
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             KernelEvents::VIEW => [
  19.                 ['setPassword'EventPriorities::PRE_VALIDATE],
  20.             ],
  21.         ];
  22.     }
  23.     public function setPassword(ViewEvent $event): void
  24.     {
  25.         $user $event->getControllerResult();
  26.         if ($user instanceof User && $user->getPlainPassword()) {
  27.             $plaintextPassword $user->getPlainPassword();
  28.             $hashedPassword $this->passwordHasher->hashPassword(
  29.                 $user,
  30.                 $plaintextPassword
  31.             );
  32.             $user->setPassword($hashedPassword);
  33.             $user->setPlainPassword(null);
  34.         }
  35.     }
  36. }