src/EventSubscriber/AddUserSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\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 AddUserSubscriber implements EventSubscriberInterface
  10. {
  11.     private UserPasswordHasherInterface $encode;
  12.     public function __construct(UserPasswordHasherInterface $encode)
  13.     {
  14.         $this->encode $encode;
  15.     }
  16.     public function onKernelView(ViewEvent $event): void
  17.     {
  18.         $user $event->getControllerResult();
  19.         $method $event->getRequest()->getMethod();
  20.         if ($user instanceof User && $method === "POST") {
  21.             $pass $this->encode->hashPassword($user$user->getPassword());
  22.             $user
  23.                 ->setPassword($pass)
  24.                 ->setCreatedAt(new \DateTime('now'))
  25.                 ->setUpdatedAt(new \DateTime('now'))
  26.                 ->setRoles(['ROLE_USER'])
  27.                 ->setIsVerified(false);
  28.         }
  29.     }
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.             KernelEvents::VIEW => ['onKernelView'EventPriorities::PRE_WRITE]
  34.         ];
  35.     }
  36. }