<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use App\Service\UsersService;
use Doctrine\ORM\EntityManagerInterface;
use Hackzilla\PasswordGenerator\Generator\ComputerPasswordGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
final class CreateUserFromApiSubscriber implements EventSubscriberInterface
{
private $messageBus;
private $passwordEncoder;
private $usersService;
private $entityManager;
public function __construct(MessageBusInterface $messageBus, UserPasswordEncoderInterface $passwordEncoder, UsersService $usersService, EntityManagerInterface $entityManager)
{
$this->messageBus = $messageBus;
$this->passwordEncoder = $passwordEncoder;
$this->usersService = $usersService;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendMail', EventPriorities::POST_WRITE],
];
}
public function sendMail(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$user instanceof User || Request::METHOD_POST !== $method) {
return;
}
$generator = new ComputerPasswordGenerator();
$generator
->setOptionValue(ComputerPasswordGenerator::OPTION_UPPER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_LOWER_CASE, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_NUMBERS, true)
->setOptionValue(ComputerPasswordGenerator::OPTION_SYMBOLS, false)
->setOptionValue(ComputerPasswordGenerator::OPTION_LENGTH, 8)
;
$plainPassword = $generator->generatePassword();
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
$plainPassword
));
$this->entityManager->persist($user);
$this->entityManager->flush();
$message = $this->usersService->preparePreviousEmail($user, $plainPassword);
$this->messageBus->dispatch($message);
}
}