<?php
namespace App\Listener;
use App\Entity\MailArchive\Message;
use App\Service\Mailer;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
class MailArchiveListener implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var Mailer
*/
private $mailer;
/**
* @var string
*/
private $fileStorage;
public function getSubscribedEvents()
{
return [Events::postLoad];
}
public function __construct(EntityManagerInterface $em, Mailer $mailer, string $fileStorage)
{
$this->em = $em;
$this->mailer = $mailer;
$this->fileStorage = $fileStorage;
}
private function flushArchive()
{
$this->mailer->flushArchive();
}
public function onKernelTerminate(TerminateEvent $event)
{
$this->flushArchive();
}
public function onConsoleTerminate(ConsoleTerminateEvent $event)
{
$this->flushArchive();
}
public function postLoad(LifecycleEventArgs $args)
{
$message = $args->getObject();
if (!$message instanceof Message) {
return;
}
$body = sprintf('%s/mail-archive/%d.html', $this->fileStorage, $message->getId());
$export = sprintf('%s/mail-archive/%d.eml', $this->fileStorage, $message->getId());
if (is_file($body)) {
$message->setBody(file_get_contents($body));
}
if (is_file($export)) {
$message->setExport(file_get_contents($export));
}
}
}