<?php
namespace MLDev\FormBundle\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use MLDev\FormBundle\Entity\MailMessage;
use MLDev\FormBundle\Event\FormConfirmSuccessEvent;
use MLDev\FormBundle\Service\FormProvider;
use MLDev\FormBundle\Service\MailerProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Environment;
class FormConfirmSuccessSubscriber implements EventSubscriberInterface
{
/**
* @var \Symfony\Component\HttpFoundation\Request|null
*/
private $request;
/**
* @var Environment
*/
private $templating;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var FormProvider
*/
private $formProvider;
/**
* @var MailerProvider
*/
private $mailerProvider;
/**
* FormConfirmSuccessSubscriber constructor.
*/
public function __construct(
EntityManagerInterface $entityManager,
RequestStack $requestStack,
Environment $twig,
FormProvider $formProvider,
MailerProvider $mailerProvider
) {
$this->request = $requestStack->getCurrentRequest();
$this->templating = $twig;
$this->entityManager = $entityManager;
$this->formProvider = $formProvider;
$this->mailerProvider = $mailerProvider;
}
public function doSaveMessageInDatabase(FormConfirmSuccessEvent $event)
{
$name = $event->getName();
$data = $event->getData();
$config = $this->formProvider->getFormConfigByName($name);
$subject = $config['settings']['subject'] ?? 'unknown';
$data = array_filter($data, function ($value) {
return !$value instanceof UploadedFile;
});
$entity = new MailMessage($subject, $data, $this->request->cookies->all());
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
public function doNotificationToEmail(FormConfirmSuccessEvent $event)
{
$name = $event->getName();
$data = $event->getData();
list('settings' => $settings) = $this->formProvider->getFormConfigByName($name);
list('subject' => $subject, 'emails' => $recipients, 'templates' => $templates) = $settings;
/** @var UploadedFile[] $files */
$files = array_filter($data, function ($value) {
return $value instanceof UploadedFile;
});
$body = $this->templating->render(
$templates['letter'], [
'config' => $settings,
'formData' => $data
]
);
$message = $this->mailerProvider->createMessage($subject, $recipients);
$message->addPart(
$body,
'text/plain'
);
if (count($files) > 0) {
foreach ($files as $uploadedFile) {
$message->attach(
\Swift_Attachment::fromPath($uploadedFile->getRealPath())->setFilename(
$uploadedFile->getClientOriginalName()
)
);
}
}
$this->mailerProvider->send($message);
}
public static function getSubscribedEvents()
{
return [
FormConfirmSuccessEvent::EVENT_NAME => [
['doSaveMessageInDatabase', 20],
['doNotificationToEmail', 10],
]
];
}
}