src/EventListener/ClientCreatedEmail.php line 32

  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Client;
  4. use App\Event\ForgottenPasswordEvent;
  5. use App\Repository\SettingRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Component\DependencyInjection\Attribute\Autowire;
  9. use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. #[AsEventListener(eventForgottenPasswordEvent::NAMEmethod'forgottenPassword')]
  12. class ClientCreatedEmail
  13. {
  14.     public function __construct(
  15.         private readonly MailerInterface $mailer,
  16.         private readonly EntityManagerInterface $em,
  17.         private SettingRepository $settingRepository,
  18.         #[Autowire('%env(MAIL_FROM)%')]
  19.         private readonly string $mailFrom,
  20.     ) {
  21.     }
  22.     public function prePersist(Client $clientmixed $event): void
  23.     {
  24.         $this->sendPasswordEmail($client);
  25.     }
  26.     public function forgottenPassword(ForgottenPasswordEvent $event): void
  27.     {
  28.         $client $event->getClient();
  29.         $this->sendPasswordEmail($client);
  30.         $this->em->persist($client);
  31.         $this->em->flush();
  32.     }
  33.     private function sendPasswordEmail(Client $client): void
  34.     {
  35.         $setting $this->settingRepository->findOneBy([]);
  36.         if (null === $client->getPasswordToken()) {
  37.             $client->generatePasswordToken();
  38.         }
  39.         $email $client->getUtilisateur()->getEmail();
  40.         if (null !== $email) {
  41.             $email = (new TemplatedEmail())
  42.                 ->from($this->mailFrom)
  43.                 ->to($email)
  44.                 ->subject($setting->getName().' - Création de votre mot de passe')
  45.                 ->text('Sending emails is fun again!')
  46.                 ->htmlTemplate('emails/client_password.html.twig')
  47.                 ->context(['client' => $client])
  48.             ;
  49.             $this->mailer->send($email);
  50.         }
  51.     }
  52. }