<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Rdv;
use App\Repository\UserRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class RdvCreatedSubscriber implements EventSubscriberInterface
{
private $mailer;
private $userRepository;
public function __construct(\Swift_Mailer $mailer,UserRepository $userRepository)
{
$this->mailer = $mailer;
$this->userRepository = $userRepository;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendMail', EventPriorities::POST_WRITE],
];
}
public function sendMail(ViewEvent $event): void
{
$rdv = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$rdv instanceof Rdv || Request::METHOD_POST !== $method) {
return;
}
$admins = $this->userRepository->findBy(['roles'=> ["ROLE_ADMIN"]]);
$emails = [];
foreach ($admins as $admin){
$emails[] = $admin->getEmail();
}
$message = (new \Swift_Message("Un nouveau Rendez-vous venant de l'application mobile E-lavandiere"))
->setTo($emails)
->setBody(sprintf('le client %s %s souhaite prendre un rendez-vous le %s.', $rdv->getUser()->getFirstname(),$rdv->getUser()->getLastname(),$rdv->getCreatedAt()->format('d/m/Y')));
$this->mailer->send($message);
}
}