Passed
Push — master ( 505a31...09a556 )
by Chris
03:27
created

SparkPostCourier::buildAttachments()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Courier;
6
7
use Courier\Exceptions\TransmissionException;
8
use Courier\Exceptions\UnsupportedContentException;
9
use Courier\Exceptions\ValidationException;
10
use PhpEmail\Address;
11
use PhpEmail\Content;
12
use PhpEmail\Email;
13
use Psr\Log\LoggerInterface;
14
use Psr\Log\NullLogger;
15
use SparkPost\SparkPost;
16
use SparkPost\SparkPostException;
17
use SparkPost\SparkPostResponse;
18
19
/**
20
 * A courier implementation using SparkPost as the third-party provider. This library uses the web API and the
21
 * php-sparkpost library to send transmissions.
22
 *
23
 * An important note is that while the SparkPost API does not support sending attachments on templated transmissions,
24
 * this API simulates the feature by creating an inline template based on the defined template using the API. In this
25
 * case, all template variables will be sent as expected, but tracking/reporting may not work as expected within
26
 * SparkPost.
27
 */
28
class SparkPostCourier implements ConfirmingCourier
29
{
30
    use SavesReceipts;
31
32
    const RECIPIENTS        = 'recipients';
33
    const CC                = 'cc';
34
    const BCC               = 'bcc';
35
    const REPLY_TO          = 'reply_to';
36
    const SUBSTITUTION_DATA = 'substitution_data';
37
38
    const CONTENT       = 'content';
39
    const FROM          = 'from';
40
    const SUBJECT       = 'subject';
41
    const HTML          = 'html';
42
    const TEXT          = 'text';
43
    const INLINE_IMAGES = 'inline_images';
44
    const ATTACHMENTS   = 'attachments';
45
    const TEMPLATE_ID   = 'template_id';
46
47
    const HEADERS   = 'headers';
48
    const CC_HEADER = 'CC';
49
50
    const ADDRESS       = 'address';
51
    const CONTACT_NAME  = 'name';
52
    const CONTACT_EMAIL = 'email';
53
    const HEADER_TO     = 'header_to';
54
55
    const ATTACHMENT_NAME = 'name';
56
    const ATTACHMENT_TYPE = 'type';
57
    const ATTACHMENT_DATA = 'data';
58
59
    /**
60
     * @var SparkPost
61
     */
62
    private $sparkPost;
63
64
    /**
65
     * @var LoggerInterface
66
     */
67
    private $logger;
68
69
    /**
70
     * @param SparkPost       $sparkPost
71
     * @param LoggerInterface $logger
72
     */
73 12
    public function __construct(SparkPost $sparkPost, LoggerInterface $logger = null)
74
    {
75 12
        $this->sparkPost = $sparkPost;
76 12
        $this->logger    = $logger ?: new NullLogger();
77
    }
78
79 12
    public function deliver(Email $email): void
80
    {
81 12
        if (!$this->supportsContent($email->getContent())) {
82 1
            throw new UnsupportedContentException($email->getContent());
83
        }
84
85 11
        $mail = $this->prepareEmail($email);
86 11
        $mail = $this->prepareContent($email, $mail);
87
88 9
        $response = $this->send($mail);
89
90 8
        $this->saveReceipt($email, $response->getBody()['results']['id']);
91
    }
92
93
    /**
94
     * @param array $mail
95
     *
96
     * @return SparkPostResponse
97
     */
98 9
    protected function send(array $mail): SparkPostResponse
99
    {
100 9
        $promise = $this->sparkPost->transmissions->post($mail);
101
102
        try {
103 9
            return $promise->wait();
104 1
        } catch (SparkPostException $e) {
105 1
            $this->logger->error(
106 1
                'Received status {code} from SparkPost with body: {body}',
107
                [
108 1
                    'code' => $e->getCode(),
109 1
                    'body' => $e->getBody(),
110
                ]
111
            );
112
113 1
            throw new TransmissionException($e->getCode(), $e);
114
        }
115
    }
116
117
    /**
118
     * @return array
119
     */
120 12
    protected function supportedContent(): array
121
    {
122
        return [
123 12
            Content\EmptyContent::class,
124
            Content\Contracts\SimpleContent::class,
125
            Content\Contracts\TemplatedContent::class,
126
        ];
127
    }
128
129
    /**
130
     * Determine if the content is supported by this courier.
131
     *
132
     * @param Content $content
133
     *
134
     * @return bool
135
     */
136 12
    protected function supportsContent(Content $content): bool
137
    {
138 12
        foreach ($this->supportedContent() as $contentType) {
139 12
            if ($content instanceof $contentType) {
140 12
                return true;
141
            }
142
        }
143
144 1
        return false;
145
    }
146
147
    /**
148
     * @param Email $email
149
     *
150
     * @return array
151
     */
152 11
    protected function prepareEmail(Email $email): array
153
    {
154 11
        $message  = [];
155 11
        $headerTo = $this->buildHeaderTo($email);
156
157 11
        $message[self::RECIPIENTS] = [];
158
159 11
        foreach ($email->getToRecipients() as $recipient) {
160 11
            $message[self::RECIPIENTS][] = $this->createAddress($recipient, $headerTo);
161
        }
162
163 11
        foreach ($email->getCcRecipients() as $recipient) {
164 3
            $message[self::RECIPIENTS][] = $this->createAddress($recipient, $headerTo);
165
        }
166
167 11
        foreach ($email->getBccRecipients() as $recipient) {
168 1
            $message[self::RECIPIENTS][] = $this->createAddress($recipient, $headerTo);
169
        }
170
171 11
        return $message;
172
    }
173
174
    /**
175
     * @param Email $email
176
     * @param array $message
177
     *
178
     * @return array
179
     */
180 11
    protected function prepareContent(Email $email, array $message): array
181
    {
182
        switch (true) {
183 11
            case $email->getContent() instanceof Content\Contracts\TemplatedContent:
184 7
                $message[self::CONTENT]           = $this->buildTemplateContent($email);
185 5
                $message[self::SUBSTITUTION_DATA] = $this->buildTemplateData($email);
186
187 5
                break;
188
189 4
            case $email->getContent() instanceof Content\EmptyContent:
190 2
                $email->setContent(new Content\SimpleContent(
191 2
                    new Content\SimpleContent\Message(''),
192 2
                    new Content\SimpleContent\Message('')
193
                ));
194
195 2
                $message[self::CONTENT] = $this->buildSimpleContent($email);
196
197 2
                break;
198
199 2
            case $email->getContent() instanceof Content\SimpleContent:
200 2
                $message[self::CONTENT] = $this->buildSimpleContent($email);
201
        }
202
203 9
        return $message;
204
    }
205
206
    /**
207
     * Attempt to create template data using the from, subject and reply to, which SparkPost considers to be
208
     * part of the templates substitutable content.
209
     *
210
     * @param Email $email
211
     *
212
     * @return array
213
     */
214 5
    protected function buildTemplateData(Email $email): array
215
    {
216
        /** @var Content\TemplatedContent $emailContent */
217 5
        $emailContent = $email->getContent();
218 5
        $templateData = $emailContent->getTemplateData();
219
220 5
        if ($email->getReplyTos()) {
221 3
            $replyTos = $email->getReplyTos();
222 3
            $first    = reset($replyTos);
223
224 3
            if (!array_key_exists('replyTo', $templateData)) {
225 3
                $templateData['replyTo'] = $first->toRfc2822();
226
            }
227
        }
228
229 5
        if (!array_key_exists('fromName', $templateData)) {
230 5
            $templateData['fromName'] = $email->getFrom()->getName();
231
        }
232
233 5
        if (!array_key_exists('fromEmail', $templateData)) {
234 5
            $templateData['fromEmail'] = explode('@', $email->getFrom()->getEmail())[0];
235
        }
236
237 5
        if (!array_key_exists('fromDomain', $templateData)) {
238 5
            $templateData['fromDomain'] = explode('@', $email->getFrom()->getEmail())[1];
239
        }
240
241 5
        if (!array_key_exists('subject', $templateData)) {
242 5
            $templateData['subject'] = $email->getSubject();
243
        }
244
245
        // @TODO Remove this variable once SparkPost CC headers work properly for templates
246 5
        if (!array_key_exists('ccHeader', $templateData)) {
247 5
            if ($header = $this->buildCcHeader($email)) {
248 2
                $templateData['ccHeader'] = $header;
249
            }
250
        }
251
252 5
        return $templateData;
253
    }
254
255
    /**
256
     * @param Email $email
257
     *
258
     * @return array
259
     */
260 7
    protected function buildTemplateContent(Email $email): array
261
    {
262
        $content = [
263 7
            self::TEMPLATE_ID => $email->getContent()->getTemplateId(),
264
        ];
265
266 7
        $content[self::HEADERS] = $this->getContentHeaders($email);
267
268 7
        if ($email->getAttachments()) {
269
            /*
270
             * SparkPost does not currently support sending attachments with templated emails. For this reason,
271
             * we will instead get the template from SparkPost and create a new inline template using the information
272
             * from it instead.
273
             */
274 5
            $template    = $this->getTemplate($email);
275 4
            $inlineEmail = clone $email;
276
277
            $inlineEmail
278 4
                ->setSubject($template[self::SUBJECT])
279 4
                ->setContent($this->getInlineContent($template));
280
281
            // If the from contains a templated from, it should be actively replaced now to avoid validation errors.
282 4
            if (strpos($template[self::FROM][self::CONTACT_EMAIL], '{{') !== false) {
283 2
                $inlineEmail->setFrom($email->getFrom());
284
            } else {
285 2
                $inlineEmail->setFrom(
286 2
                    new Address(
287 2
                        $template[self::FROM][self::CONTACT_EMAIL],
288 2
                        $template[self::FROM][self::CONTACT_NAME]
289
                    )
290
                );
291
            }
292
293
            // If the form contains a templated replyTo, it should be actively replaced now to avoid validation errors.
294 4
            if (array_key_exists(self::REPLY_TO, $template)) {
295 4
                if (strpos($template[self::REPLY_TO], '{{') !== false) {
296 2
                    if (empty($email->getReplyTos())) {
297 1
                        throw new ValidationException('Reply to is templated but no value was given');
298
                    }
299
300 1
                    $inlineEmail->setReplyTos($email->getReplyTos()[0]);
301
                } else {
302 2
                    $inlineEmail->setReplyTos(Address::fromString($template[self::REPLY_TO]));
303
                }
304
            }
305
306 3
            $content = $this->buildSimpleContent($inlineEmail);
307
308
            // If the template AND content include headers, merge them
309
            // if only the template includes headers, then just use that
310 3
            if (array_key_exists(self::HEADERS, $template) && array_key_exists(self::HEADERS, $content)) {
311 3
                $content[self::HEADERS] = array_merge($template[self::HEADERS], $content[self::HEADERS]);
312
            } elseif (array_key_exists(self::HEADERS, $template)) {
313
                $content[self::HEADERS] = $template[self::HEADERS];
314
            }
315
        }
316
317 5
        return $content;
318
    }
319
320
    /**
321
     * @param Email $email
322
     *
323
     * @return array
324
     */
325 7
    protected function buildSimpleContent(Email $email): array
326
    {
327 7
        $replyTo = null;
328 7
        if (!empty($email->getReplyTos())) {
329
            // SparkPost only supports a single reply-to
330 4
            $replyTos = $email->getReplyTos();
331 4
            $first    = reset($replyTos);
332
333 4
            $replyTo = $first->toRfc2822();
334
        }
335
336
        /** @var Content\Contracts\SimpleContent $emailContent */
337 7
        $emailContent = $email->getContent();
338
339
        $content = [
340 7
            self::FROM          => [
341 7
                self::CONTACT_NAME  => $email->getFrom()->getName(),
342 7
                self::CONTACT_EMAIL => $email->getFrom()->getEmail(),
343
            ],
344 7
            self::SUBJECT       => $email->getSubject(),
345 7
            self::HTML          => $emailContent->getHtml() !== null ? $emailContent->getHtml()->getBody() : null,
346 7
            self::TEXT          => $emailContent->getText() !== null ? $emailContent->getText()->getBody() : null,
347 7
            self::ATTACHMENTS   => $this->buildAttachments($email),
348 7
            self::INLINE_IMAGES => $this->buildInlineAttachments($email),
349 7
            self::REPLY_TO      => $replyTo,
350
        ];
351
352 7
        $content[self::HEADERS] = $this->getContentHeaders($email);
353
354 7
        return $content;
355
    }
356
357 11
    protected function getContentHeaders(Email $email): array
358
    {
359 11
        $headers = [];
360
361 11
        if ($ccHeader = $this->buildCcHeader($email)) {
362 3
            $headers[self::CC_HEADER] = $ccHeader;
363
        }
364
365 11
        foreach ($email->getHeaders() as $header) {
366 1
            $headers[$header->getField()] = $header->getValue();
367
        }
368
369 11
        return $headers;
370
    }
371
372
    /**
373
     * Create the SimpleContent based on the SparkPost template data.
374
     *
375
     * @param array $template
376
     *
377
     * @return Content\SimpleContent
378
     */
379 4
    protected function getInlineContent(array $template): Content\SimpleContent
380
    {
381 4
        $htmlContent = null;
382 4
        if (array_key_exists(self::HTML, $template)) {
383 4
            $htmlContent = new Content\SimpleContent\Message($template[self::HTML]);
384
        }
385
386 4
        $textContent = null;
387 4
        if (array_key_exists(self::TEXT, $template)) {
388
            $textContent = new Content\SimpleContent\Message($template[self::TEXT]);
389
        }
390
391 4
        return new Content\SimpleContent($htmlContent, $textContent);
392
    }
393
394
    /**
395
     * Get the template content from SparkPost.
396
     *
397
     * @param Email $email
398
     *
399
     * @throws TransmissionException
400
     *
401
     * @return array
402
     */
403 5
    private function getTemplate(Email $email): array
404
    {
405
        try {
406 5
            $response = $this->sparkPost->syncRequest('GET', "templates/{$email->getContent()->getTemplateId()}");
407
408 4
            return $response->getBody()['results'][self::CONTENT];
409 1
        } catch (SparkPostException $e) {
410 1
            $this->logger->error(
411 1
                'Received status {code} from SparkPost while retrieving template with body: {body}',
412
                [
413 1
                    'code' => $e->getCode(),
414 1
                    'body' => $e->getBody(),
415
                ]
416
            );
417
418 1
            throw new TransmissionException($e->getCode(), $e);
419
        }
420
    }
421
422
    /**
423
     * @param Email $email
424
     *
425
     * @return array
426
     */
427 7
    private function buildAttachments(Email $email): array
428
    {
429 7
        $attachments = [];
430
431 7
        foreach ($email->getAttachments() as $attachment) {
432 4
            $attachments[] = [
433 4
                self::ATTACHMENT_NAME => $attachment->getName(),
434 4
                self::ATTACHMENT_TYPE => $attachment->getContentType(),
435 4
                self::ATTACHMENT_DATA => $attachment->getBase64Content(),
436
            ];
437
        }
438
439 7
        return $attachments;
440
    }
441
442
    /**
443
     * @param Email $email
444
     *
445
     * @return array
446
     */
447 7
    private function buildInlineAttachments(Email $email): array
448
    {
449 7
        $inlineAttachments = [];
450
451 7
        foreach ($email->getEmbedded() as $embedded) {
452 2
            $inlineAttachments[] = [
453 2
                self::ATTACHMENT_NAME => $embedded->getContentId(),
454 2
                self::ATTACHMENT_TYPE => $embedded->getContentType(),
455 2
                self::ATTACHMENT_DATA => $embedded->getBase64Content(),
456
            ];
457
        }
458
459 7
        return $inlineAttachments;
460
    }
461
462
    /**
463
     * @param Address $address
464
     * @param string  $headerTo
465
     *
466
     * @return array
467
     */
468 11
    private function createAddress(Address $address, string $headerTo): array
469
    {
470
        return [
471 11
            self::ADDRESS => [
472 11
                self::CONTACT_EMAIL => $address->getEmail(),
473 11
                self::HEADER_TO     => $headerTo,
474
            ],
475
        ];
476
    }
477
478
    /**
479
     * Build a string representing the header_to field of this email.
480
     *
481
     * @param Email $email
482
     *
483
     * @return string
484
     */
485
    private function buildHeaderTo(Email $email): string
486
    {
487 11
        return implode(',', array_map(function (Address $address) {
488 11
            return $address->toRfc2822();
489 11
        }, $email->getToRecipients()));
490
    }
491
492
    /**
493
     * Build a string representing the CC header for this email.
494
     *
495
     * @param Email $email
496
     *
497
     * @return string
498
     */
499
    private function buildCcHeader(Email $email): string
500
    {
501 11
        return implode(',', array_map(function (Address $address) {
502 3
            return $address->toRfc2822();
503 11
        }, $email->getCcRecipients()));
504
    }
505
}
506