Mailjet::send()   F
last analyzed

Complexity

Conditions 11
Paths 512

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 20.5265

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 11
eloc 30
nc 512
nop 1
dl 0
loc 53
ccs 16
cts 28
cp 0.5714
crap 20.5265
rs 3.8277
c 2
b 1
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Omnimail;
4
5
use Omnimail\Exception\InvalidRequestException;
6
use Psr\Log\LoggerInterface;
7
use Mailjet\Resources;
8
use Mailjet\Client;
9
10
class Mailjet implements MailerInterface
11
{
12
    private $apikey;
13
    private $apisecret;
14
    private $logger;
15
    private $mailjet;
16
17
    public function getApiKey()
18
    {
19
        return $this->apikey;
20
    }
21
22
    public function setApiKey($apikey)
23
    {
24
        $this->apikey = $apikey;
25
        $this->mailjet = new Client($apikey, $this->apisecret);
26
    }
27
28
    public function getApiSecret()
29
    {
30
        return $this->apisecret;
31
    }
32
33
    public function setApiSecret($apisecret)
34
    {
35
        $this->apisecret = $apisecret;
36
        $this->mailjet = new Client($this->apikey, $apisecret);
37
    }
38
39
    public function getLogger()
40
    {
41
        return $this->logger;
42
    }
43
44
    public function setLogger($logger)
45
    {
46
        $this->logger = $logger;
47
    }
48
49
    /**
50
     * @param string $apikey
51
     * @param string $apisecret
52
     * @param LoggerInterface|null $logger
53
     */
54 1
    public function __construct($apikey = null, $apisecret = null, LoggerInterface $logger = null)
55
    {
56 1
        $this->apikey = $apikey;
57 1
        $this->apisecret = $apisecret;
58 1
        $this->logger = $logger;
59 1
        $this->mailjet = new Client($apikey, $apisecret);
60 1
    }
61
62 1
    /**
63
     * @param EmailInterface $email
64 1
     * @throws InvalidRequestException
65
     */
66
    public function send(EmailInterface $email)
67 1
    {
68 1
        $from = $email->getFrom();
69 1
70
        $body = [
71
            'FromEmail' => $from['email'],
72 1
            'Subject' => $email->getSubject(),
73
            'Recipients' => $this->mapEmails($email->getTos())
74
        ];
75
76 1
        if (!empty($from['name'])) {
77
            $body['FromName'] = $from['name'];
78
        }
79
80
        if ($email->getReplyTos()) {
81
            $body['Headers'] = [
82 1
                'Reply-To' => $this->mapEmailsString($email->getReplyTos())
83
            ];
84
        }
85
86 1
        if ($email->getCcs()) {
87
            $body['Cc'] = $this->mapEmails($email->getCcs());
88
        }
89
90 1
        if ($email->getBccs()) {
91 1
            $body['Bcc'] = $this->mapEmails($email->getBccs());
92
        }
93
94 1
        if ($email->getTextBody()) {
95
            $body['Text-part'] = $email->getTextBody();
96
        }
97
98 1
        if ($email->getHtmlBody()) {
99
            $body['Html-part'] = $email->getHtmlBody();
100
        }
101
102
        if ($email->getAttachments()) {
103 1
            $body['Attachments'] = $this->mapAttachments($email->getAttachments());
104 1
            $body['Inline_attachments'] = $this->mapInlineAttachments($email->getAttachments());
105
        }
106 1
107
        $this->mailjet->setTimeout(20);
108
        $response = $this->mailjet->post(Resources::$Email, ['body' => $body]);
109
110
        if ($response->success()) {
111 1
            if ($this->logger) {
112
                $this->logger->info("Email sent: '{$email->getSubject()}'", $email->toArray());
113
            }
114 1
        } else {
115
            if ($this->logger) {
116
                $this->logger->error("Email error: '{$response->getReasonPhrase()}'", $email->toArray());
117
            }
118
            throw new InvalidRequestException($response->getReasonPhrase());
119
        }
120
    }
121
122
    /**
123
     * @param AttachmentInterface[] $attachments
124
     * @return array|null
125
     */
126
    private function mapAttachments(array $attachments)
127
    {
128
        if (null === $attachments || !is_array($attachments) || !count($attachments)) {
0 ignored issues
show
introduced by
The condition is_array($attachments) is always true.
Loading history...
129
            return null;
130
        }
131
132
        $finalAttachments = [];
133
        /** @var AttachmentInterface $attachment */
134
        foreach ($attachments as $attachment) {
135
            if ($attachment->getContentId()) {
136
                continue;
137
            }
138
            $finalAttachment = $this->mapAttachment($attachment);
139
            if ($finalAttachment) {
140
                $finalAttachments[] = $finalAttachment;
141
            }
142
        }
143
        return $finalAttachments;
144
    }
145
146
    /**
147
     * @param AttachmentInterface[] $attachments
148
     * @return array|null
149
     */
150
    private function mapInlineAttachments(array $attachments)
151
    {
152
        if (null === $attachments || !is_array($attachments) || !count($attachments)) {
0 ignored issues
show
introduced by
The condition is_array($attachments) is always true.
Loading history...
153
            return null;
154
        }
155
156
        $finalAttachments = [];
157
        /** @var AttachmentInterface $attachment */
158
        foreach ($attachments as $attachment) {
159
            if (!$attachment->getContentId()) {
160
                continue;
161
            }
162
            $finalAttachment = $this->mapAttachment($attachment);
163
            if ($finalAttachment) {
164
                $finalAttachments[] = $finalAttachment;
165
            }
166
        }
167
        return $finalAttachments;
168
    }
169
170
    private function mapAttachment(AttachmentInterface $attachment)
171
    {
172
        $finalAttachment = [
173
            'Content-type' => $attachment->getMimeType(),
174
            'Filename' => $attachment->getName()
175
        ];
176
        if ($attachment->getPath()) {
177
            $finalAttachment['content'] = base64_encode(file_get_contents($attachment->getPath()));
178
        } elseif ($attachment->getContent()) {
179
            $finalAttachment['content'] = base64_encode($attachment->getContent());
180
        }
181
182
        if ($attachment->getContentId()) {
183
            $finalAttachment['Filename'] = $attachment->getContentId();
184
        }
185
186
        return $finalAttachment;
187
    }
188
189 1
    /**
190
     * @param array $emails
191 1
     * @return array
192 1
     */
193 1
    private function mapEmails(array $emails)
194
    {
195 1
        $returnValue = [];
196
        foreach ($emails as $email) {
197
            $returnValue[] = $this->mapEmail($email);
198
        }
199
        return $returnValue;
200
    }
201
202 1
    /**
203
     * @param array $email
204 1
     * @return array
205 1
     */
206
    private function mapEmail(array $email)
207
    {
208 1
        $returnValue = ['Email' => $email['email']];
209
        if ($email['name']) {
210
            $returnValue['Name'] = $email['name'];
211
        }
212
        return $returnValue;
213
    }
214
215
    /**
216
     * @param array $emails
217
     * @return string
218
     */
219
    private function mapEmailsString(array $emails)
220
    {
221
        $returnValue = '';
222
        foreach ($emails as $email) {
223
            $returnValue .= $this->mapEmailString($email) . ', ';
224
        }
225
        return $returnValue ? substr($returnValue, 0, -2) : '';
226
    }
227
228
    /**
229
     * @param array $email
230
     * @return string
231
     */
232
    private function mapEmailString(array $email)
233
    {
234
        return !empty($email['name']) ? "'{$email['name']}' <{$email['email']}>" : $email['email'];
235
    }
236
}
237