1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Sonata Project package. |
7
|
|
|
* |
8
|
|
|
* (c) Thomas Rabaix <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Sonata\NotificationBundle\Consumer; |
15
|
|
|
|
16
|
|
|
use Sonata\NotificationBundle\Model\MessageInterface; |
17
|
|
|
|
18
|
|
|
class SwiftMailerConsumer implements ConsumerInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var \Swift_Mailer |
22
|
|
|
*/ |
23
|
|
|
protected $mailer; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param \Swift_Mailer $mailer |
27
|
|
|
*/ |
28
|
|
|
public function __construct(\Swift_Mailer $mailer) |
29
|
|
|
{ |
30
|
|
|
$this->mailer = $mailer; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
*/ |
36
|
|
|
public function process(ConsumerEvent $event): void |
37
|
|
|
{ |
38
|
|
|
if (!$this->mailer->getTransport()->isStarted()) { |
39
|
|
|
$this->mailer->getTransport()->start(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$exception = false; |
43
|
|
|
|
44
|
|
|
try { |
45
|
|
|
$this->sendEmail($event->getMessage()); |
46
|
|
|
} catch (\Exception $e) { |
47
|
|
|
$exception = $e; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$this->mailer->getTransport()->stop(); |
51
|
|
|
|
52
|
|
|
if ($exception) { |
53
|
|
|
throw $exception; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param MessageInterface $message |
59
|
|
|
*/ |
60
|
|
|
private function sendEmail(MessageInterface $message): void |
61
|
|
|
{ |
62
|
|
|
$mail = $this->mailer->createMessage() |
63
|
|
|
->setSubject($message->getValue('subject')) |
64
|
|
|
->setFrom([$message->getValue(['from', 'email']) => $message->getValue(['from', 'name'])]) |
65
|
|
|
->setTo($message->getValue('to')); |
66
|
|
|
|
67
|
|
|
if ($replyTo = $message->getValue('replyTo')) { |
68
|
|
|
$mail->setReplyTo($replyTo); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if ($cc = $message->getValue('cc')) { |
72
|
|
|
$mail->setCc($cc); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
if ($bcc = $message->getValue('bcc')) { |
76
|
|
|
$mail->setBcc($bcc); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if ($text = $message->getValue(['message', 'text'])) { |
80
|
|
|
$mail->addPart($text, 'text/plain'); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if ($html = $message->getValue(['message', 'html'])) { |
84
|
|
|
$mail->addPart($html, 'text/html'); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
if ($attachment = $message->getValue(['attachment', 'file'])) { |
88
|
|
|
$attachmentName = $message->getValue(['attachment', 'name']); |
89
|
|
|
|
90
|
|
|
$mail->attach(new \Swift_Attachment($attachment, $attachmentName)); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
$this->mailer->send($mail); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|