src/EventSubscriber/UserRegisterSubscriber.php line 33

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\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. class UserRegisterSubscriber implements EventSubscriberInterface
  11. {
  12.     private $userPasswordHasher;
  13.     public function __construct(
  14.         UserPasswordHasherInterface $userPasswordHasher
  15.     )
  16.     {
  17.         $this->userPasswordHasher $userPasswordHasher;
  18.     }
  19.     public static function getSubscribedEvents()
  20.     {
  21.         return [
  22.             KernelEvents::VIEW => ['userRegistered'EventPriorities::PRE_WRITE],
  23.         ];
  24.     }
  25.     public function userRegistered(ViewEvent $event)
  26.     {
  27.         $user $event->getControllerResult();
  28.         $method $event->getRequest()
  29.             ->getMethod();
  30.         if (!$user instanceof User ||
  31.             !in_array($method, [Request::METHOD_POST])) {
  32.             return;
  33.         }
  34.         $user->setPassword(
  35.             $this->userPasswordHasher->hashPassword(
  36.                 $user,
  37.                 $user->getPassword()
  38.             )
  39.         );
  40.     }
  41. }