<?php declare(strict_types=1);
namespace App\EventListener;
use App\Entity\OpensystemLog;
use App\Event\OpenSystemEvent;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Twig\Environment;
/**
* Class ApidaeSubscriber
* @package App\EventListener
*/
class OpensystemSubscriber implements EventSubscriberInterface
{
/** @var EntityManagerInterface */
private $entityManager;
private $mailer;
private $logger;
private $template;
/**
* UserSubscriber constructor.
*
* @param EntityManagerInterface $entityManager
* @param \Swift_Mailer $mailer
* @param LoggerInterface $logger
* @param Environment $template
*/
public function __construct(EntityManagerInterface $entityManager,
\Swift_Mailer $mailer,
LoggerInterface $logger,
Environment $template)
{
$this->entityManager = $entityManager;
$this->mailer = $mailer;
$this->logger = $logger;
$this->template = $template;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
OpenSystemEvent::OPENSYSTEM_AVAILABILITY_ERROR => ['availabilityError'],
OpenSystemEvent::OPENSYSTEM_AVAILABILITY_INFO => ['availabilityInfo']
];
}
/**
* @param OpenSystemEvent $event
*/
public function availabilityError(OpenSystemEvent $event)
{
$apiLog = new OpensystemLog();
$apiLog->setState(OpenSystemEvent::OPENSYSTEM_AVAILABILITY_ERROR);
$apiLog->setMessage($event->getMessage());
$apiLog->setCode($event->getCode());
$apiLog->setObjectId($event->getExperience()->getId());
$this->entityManager->persist($apiLog);
$this->entityManager->flush();
}
/**
* @param OpenSystemEvent $event
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
public function availabilityInfo(OpenSystemEvent $event)
{
$returncode = $event->getCode();
$apiLog = new OpensystemLog();
$apiLog->setState(OpenSystemEvent::OPENSYSTEM_AVAILABILITY_INFO);
$apiLog->setMessage($event->getMessage());
$apiLog->setCode($returncode);
$apiLog->setObjectId($event->getExperience()->getId());
$this->entityManager->persist($apiLog);
$this->entityManager->flush();
if ($returncode>=0){
switch ($returncode){
case 0:
$subject = '[evasion] Une expérience a été re-publiée';
$template = 'email/republish.html.twig';
break;
case 1:
$subject = '[evasion] Une expérience a été marquée indisponible';
$template = 'email/unavailability.html.twig';
break;
}
$message = (new \Swift_Message())
->setSubject($subject)
->setTo([ '[email protected]', '[email protected]', '[email protected]', '[email protected]' ])
->setBcc([ '[email protected]', '[email protected]' ])
->setFrom(['[email protected]' => 'Isère Attractivité'])
->setBody(
$this->template->render($template, [
'experience' => $event->getExperience(),
]),
'text/html'
)
;
try {
$this->mailer->send($message);
} catch (\Exception $e) {
$this->logger->error('Error sending email', ['message' => $e->getMessage(), 'code' => $e->getCode()]);
}
}
}
}