This repository has been archived by the owner on Feb 6, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathEmailSenderListener.php
88 lines (76 loc) · 3.08 KB
/
EmailSenderListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\SwiftmailerBundle\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Sends emails for the memory spool.
*
* Emails are sent on the kernel.terminate event.
*
* @author Fabien Potencier <[email protected]>
*/
class EmailSenderListener implements EventSubscriberInterface
{
private $container;
private $logger;
private $wasExceptionThrown = false;
public function __construct(ContainerInterface $container, LoggerInterface $logger = null)
{
$this->container = $container;
$this->logger = $logger;
}
public function onException()
{
$this->wasExceptionThrown = true;
}
public function onTerminate()
{
if (!$this->container->has('mailer') || $this->wasExceptionThrown) {
return;
}
$mailers = array_keys($this->container->getParameter('swiftmailer.mailers'));
foreach ($mailers as $name) {
if (method_exists($this->container, 'initialized') ? $this->container->initialized(sprintf('swiftmailer.mailer.%s', $name)) : true) {
if ($this->container->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name))) {
$mailer = $this->container->get(sprintf('swiftmailer.mailer.%s', $name));
$transport = $mailer->getTransport();
if ($transport instanceof \Swift_Transport_SpoolTransport) {
$spool = $transport->getSpool();
if ($spool instanceof \Swift_MemorySpool) {
try {
$spool->flushQueue($this->container->get(sprintf('swiftmailer.mailer.%s.transport.real', $name)));
} catch (\Swift_TransportException $exception) {
if (null !== $this->logger) {
$this->logger->error(sprintf('Exception occurred while flushing email queue: %s', $exception->getMessage()));
}
}
}
}
}
}
}
}
public static function getSubscribedEvents()
{
$listeners = array(
KernelEvents::EXCEPTION => 'onException',
KernelEvents::TERMINATE => 'onTerminate'
);
if (class_exists('Symfony\Component\Console\ConsoleEvents')) {
$listeners[class_exists('Symfony\Component\Console\Event\ConsoleErrorEvent') ? ConsoleEvents::ERROR : ConsoleEvents::EXCEPTION] = 'onException';
$listeners[ConsoleEvents::TERMINATE] = 'onTerminate';
}
return $listeners;
}
}