<?php
namespace App\EventListener;
use App\Service\MailerService;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\FormAnswer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
class FormAnswerCreatedListener implements EventSubscriberInterface
{
private $mailerService;
private EntityManagerInterface $entityManager;
private $validator;
public function __construct(MailerService $mailerService, EntityManagerInterface $entityManager, ValidatorInterface $validator)
{
$this->mailerService = $mailerService;
$this->entityManager = $entityManager;
$this->validator = $validator;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['saveFormAnswer', EventPriorities::POST_WRITE],
];
}
public function saveFormAnswer(ViewEvent $event)
{
$mainFormAnswer = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$mainFormAnswer instanceof FormAnswer) {
return;
}
$answerFields = $mainFormAnswer->getFormAnswerFields();
$content = "";
foreach($answerFields as $answerField){
$content .= $answerField->getFormField()->getLabel() . " - " . $answerField->getValue() . "\n";
}
$recipientEmail = $mainFormAnswer->getForm()->getSendMailAnswet();
$meiles = explode(',',$recipientEmail);
$subject = "Нова відповідь на форму - " . $mainFormAnswer->getForm()->getName();
foreach($meiles as $meil){
$this->mailerService->sendRegistrationEmail(trim($meil), $subject, $content);
}
}
}