<?php
/*
* @since 1.0.0
* @copyright Copyright (C) 2020 ArtMedia. All rights reserved.
* @website http://artmedia.biz.pl
* @author Arkadiusz Tobiasz
* @email kontakt@artmedia.biz.pl
*/
namespace App\EventSubscriber\Core;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Events\Core\CronJobAddEvent;
use App\Events\Core\MailAddEvent;
use App\Events\Core\MailQueueSendEvent;
use App\Events\Core\MailDeleteEvent;
use App\Model\Core\CronJob;
use App\Entity\Core\Mail;
use Doctrine\ORM\EntityManagerInterface;
use App\Settings\SettingsManager;
use App\Manager\Core\Mail\MailsManager;
class MailerSubscriber implements EventSubscriberInterface
{
private $em;
private $settingsManager;
private $mailsManager;
public function __construct(
MailsManager $mailsManager,
SettingsManager $settingsManager,
EntityManagerInterface $em
) {
$this->mailsManager = $mailsManager;
$this->settingsManager = $settingsManager;
$this->em = $em;
}
public static function getSubscribedEvents(): array
{
return [
CronJobAddEvent::NAME => 'onCronJobAddEvent',
MailAddEvent::NAME => 'onMailAddEvent',
MailQueueSendEvent::NAME => 'onMailQueueSendEvent',
MailDeleteEvent::NAME => 'onMailDeleteEvent',
];
}
public function onMailDeleteEvent(MailDeleteEvent $event): void
{
$period = $this->settingsManager->getValue(SettingsManager::CORE_MAILER_DELETE_PERIOD);
$this->em->getRepository(Mail::class)->onMailDeleteEvent($period);
}
public function onMailQueueSendEvent(MailQueueSendEvent $event): void
{
$limit = $this->settingsManager->getValue(SettingsManager::CORE_MAIL_BULK_LIMIT);
$mails = $this->em->getRepository(Mail::class)->getListToSend($limit);
if ($mails) {
foreach ($mails as $mail) {
$this->mailsManager->create(
$mail->getSender(),
$mail->getReceiver(),
$mail->getSubject(),
$mail->getHtml(),
$mail->getTxt(),
[],
$mail->getPriority(),
$mail->getAttachments(),
false
);
$this->mailsManager->send();
$mail->setSendDate(new \DateTime());
}
$this->em->flush();
}
}
public function onMailAddEvent(MailAddEvent $event): void
{
$this->mailsManager->create(
$event->getSender(),
$event->getReceiver(),
$event->getSubject(),
$event->getHtml(),
$event->getTxt(),
$event->getParams(),
$event->getPriority(),
);
if ($event->getAttachments()) {
foreach ($event->getAttachments() as $attachment) {
$this->mailsManager->addAttachment($attachment);
}
}
if ($event->isAddToQueue()) {
$this->mailsManager->addToQuene();
} else {
$this->mailsManager->addToQuene(true);
$this->mailsManager->send();
}
}
public function onCronJobAddEvent(CronJobAddEvent $event): void
{
$cronJob = new CronJob();
$cronJob->setName('Send mailer queue')
->setEvent(MailQueueSendEvent::NAME)
->setClass('App\Events\Core\MailQueueSendEvent')
->setInterval(5)
;
$event->addCronJob($cronJob);
$cronJob = new CronJob();
$cronJob->setName('Delete send emails')
->setEvent(MailDeleteEvent::NAME)
->setClass('App\Events\Core\MailDeleteEvent')
->setInterval(1440)
;
$event->addCronJob($cronJob);
}
}