Passed
Push — main ( 8365e4...b2f486 )
by Peter
03:33
created

Sender   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 27
c 2
b 0
f 0
dl 0
loc 86
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B send() 0 42 7
A getFailedRecipients() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Email;
6
7
use Symfony\Component\Mailer\Mailer;
8
use Symfony\Component\Mime\Address;
9
10
class Sender implements ISender
11
{
12
    protected Mailer $mailer;
13
14
    protected MessageFactory $messageFactory;
15
16
    /** @var Address[] */
17
    protected array $failedRecipients = [];
18
19
    /**
20
     * Sender constructor.
21
     *
22
     * @param Mailer         $mailer
23
     * @param MessageFactory $messageFactory
24
     */
25
    public function __construct(Mailer $mailer, MessageFactory $messageFactory)
26
    {
27
        $this->mailer         = $mailer;
28
        $this->messageFactory = $messageFactory;
29
    }
30
31
    /**
32
     * @param string       $subject
33
     * @param string       $textBody
34
     * @param string       $htmlBody
35
     * @param Address      $sender
36
     * @param Address[]    $recipients
37
     * @param Address|null $replyToAddress
38
     * @param int|null     $priority
39
     * @param array|null   $bcc
40
     * @param array|null   $cc
41
     *
42
     * @return void
43
     */
44
    public function send(
45
        string $subject,
46
        string $textBody,
47
        string $htmlBody,
48
        Address $sender,
49
        array $recipients,
50
        ?Address $replyToAddress = null,
51
        ?int $priority = null,
52
        ?array $bcc = null,
53
        ?array $cc = null,
54
    ): void {
55
        $message = $this->messageFactory->create()
56
            ->from($sender)
57
            ->subject($subject)
58
            ->text($textBody)
59
            ->html($htmlBody);
60
61
        if ($replyToAddress !== null) {
62
            $message->replyTo($replyToAddress);
63
        }
64
65
        if ($priority !== null) {
66
            $message->priority($priority);
67
        }
68
69
        if ($cc !== null) {
70
            $message->cc(...$cc);
71
        }
72
73
        if ($bcc !== null) {
74
            $message->bcc(...$bcc);
75
        }
76
77
        $this->failedRecipients = [];
78
79
        foreach ($recipients as $value) {
80
            $message->to($value);
81
82
            try {
83
                $this->mailer->send($message);
84
            } catch (\Throwable $e) {
85
                $this->failedRecipients[] = $value;
86
            }
87
        }
88
    }
89
90
    /**
91
     * @return string[]
92
     */
93
    public function getFailedRecipients(): array
94
    {
95
        return $this->failedRecipients;
96
    }
97
}
98