src/EventSubscriber/PasswordSubscriber.php line 31

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