src/EventSubscriber/CreateUserFromApiSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User;
  5. use App\Service\UsersService;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Hackzilla\PasswordGenerator\Generator\ComputerPasswordGenerator;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\Messenger\MessageBusInterface;
  13. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  14. final class CreateUserFromApiSubscriber implements EventSubscriberInterface
  15. {
  16.     private $messageBus;
  17.     private $passwordEncoder;
  18.     private $usersService;
  19.     private $entityManager;
  20.     public function __construct(MessageBusInterface $messageBusUserPasswordEncoderInterface $passwordEncoderUsersService $usersServiceEntityManagerInterface $entityManager)
  21.     {
  22.         $this->messageBus $messageBus;
  23.         $this->passwordEncoder $passwordEncoder;
  24.         $this->usersService $usersService;
  25.         $this->entityManager $entityManager;
  26.     }
  27.     public static function getSubscribedEvents()
  28.     {
  29.         return [
  30.             KernelEvents::VIEW => ['sendMail'EventPriorities::POST_WRITE],
  31.         ];
  32.     }
  33.     public function sendMail(ViewEvent $event): void
  34.     {
  35.         $user $event->getControllerResult();
  36.         $method $event->getRequest()->getMethod();
  37.         if (!$user instanceof User || Request::METHOD_POST !== $method) {
  38.             return;
  39.         }
  40.         $generator = new ComputerPasswordGenerator();
  41.         $generator
  42.             ->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASEtrue)
  43.             ->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASEtrue)
  44.             ->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERStrue)
  45.             ->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLSfalse)
  46.             ->setOptionValue(ComputerPasswordGenerator::OPTION_LENGTH8)
  47.         ;
  48.         $plainPassword $generator->generatePassword();
  49.         $user->setPassword($this->passwordEncoder->encodePassword(
  50.             $user,
  51.             $plainPassword
  52.         ));
  53.         $this->entityManager->persist($user);
  54.         $this->entityManager->flush();
  55.         $message $this->usersService->preparePreviousEmail($user$plainPassword);
  56.         $this->messageBus->dispatch($message);
  57.     }
  58. }