Completed
Push — master ( bd9b49...e48eea )
by Walter
13:41
created

SwiftMailer::sendToRecipient()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 5
nop 5
1
<?php
2
/**
3
 * Communicator (https://github.com/waltertamboer/communicator)
4
 *
5
 * @link https://github.com/waltertamboer/communicator for the canonical source repository
6
 * @copyright Copyright (c) 2017 Communicator (https://github.com/waltertamboer/communicator)
7
 * @license https://github.com/waltertamboer/communicator/blob/master/LICENSE.md MIT
8
 */
9
10
namespace Communicator\Transport\Email\Adapter;
11
12
use Communicator\Message;
13
use Communicator\Recipient\RecipientInterface;
14
use Swift_Mailer;
15
use Swift_Message;
16
17
/**
18
 * An e-mail transport that makes use of Swift Mailer.
19
 */
20
final class SwiftMailer extends AbstractAdapter
21
{
22
    /**
23
     * The mailer used to send messages.
24
     *
25
     * @var Swift_Mailer
26
     */
27
    private $mailer;
28
29
    /**
30
     * Initializes a new instance of this class.
31
     *
32
     * @param Swift_Mailer $mailer
33
     */
34
    public function __construct(Swift_Mailer $mailer)
35
    {
36
        $this->mailer = $mailer;
37
    }
38
39
    /**
40
     * Sends a message to the given recipient.
41
     *
42
     * @param RecipientInterface $recipient The recipient that should receive the message.
43
     * @param Message $message The message that should be sent.
44
     * @param string $subject The subject of the message.
45
     * @param string $text The plain text message.
46
     * @param null|string $html An optional HTML version of the message.
47
     */
48
    protected function sendToRecipient(
49
        RecipientInterface $recipient,
50
        Message $message,
51
        string $subject,
52
        string $text,
53
        ?string $html
54
    ): void {
55
        $addresses = $this->getAddresses($recipient, $message);
56
57
        foreach ($addresses as $address) {
58
            /** @var Swift_Message $emailMessage */
59
            $emailMessage = $this->mailer->createMessage();
60
            $emailMessage->setSubject($subject);
61
            $emailMessage->setTo($address);
62
            $emailMessage->setBody($text);
63
64
            if ($this->getFromAddress() !== null) {
65
                $emailMessage->setFrom($this->getFromAddress(), $this->getFromName());
66
            }
67
68
            if ($html !== null) {
69
                $emailMessage->addPart($html, 'text/html');
70
            }
71
72
            $this->mailer->send($emailMessage);
73
        }
74
    }
75
}
76