Passed
Push — master ( 3f888d...a35bef )
by Chris
07:47
created

MailjetCourier::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Camuthig\Courier\Mailjet;
6
7
use Courier\ConfirmingCourier;
8
use Courier\Exceptions\TransmissionException;
9
use Courier\Exceptions\UnsupportedContentException;
10
use Courier\SavesReceipts;
11
use Mailjet\Client;
12
use Mailjet\Resources;
13
use PhpEmail\Address;
14
use PhpEmail\Attachment;
15
use PhpEmail\Content;
16
use PhpEmail\Content\Contracts\SimpleContent;
17
use PhpEmail\Content\Contracts\TemplatedContent;
18
use PhpEmail\Content\EmptyContent;
19
use PhpEmail\Email;
20
use PhpEmail\Header;
21
use Ramsey\Uuid\Uuid;
22
23
class MailjetCourier implements ConfirmingCourier
24
{
25
    use SavesReceipts;
26
27
    /**
28
     * @var Client
29
     */
30
    protected $client;
31
32
    public function __construct(Client $client)
33
    {
34
        $this->client = $client;
35
    }
36
37
    /**
38
     * @param Email $email
39
     *
40
     * @throws TransmissionException
41
     * @throws UnsupportedContentException
42
     *
43
     * @return void
44
     */
45
    public function deliver(Email $email): void
46
    {
47
        if (!$this->supportsContent($email->getContent())) {
48
            throw new UnsupportedContentException($email->getContent());
49
        }
50
51
        $preparedEmail = $this->prepareEmail($email);
52
53
        $response = $this->client->post(Resources::$Email, ['body' => $preparedEmail], ['version' => 'v3.1']);
54
55
        if (!$response->success()) {
56
            throw new TransmissionException($response->getStatus(), new \Exception($response->getReasonPhrase()));
57
        }
58
59
        $customId = $response->getBody()['Messages'][0]['CustomID'];
60
61
        $this->saveReceipt($email, $customId);
62
    }
63
64
    protected function supportedContent(): array
65
    {
66
        return [
67
            EmptyContent::class,
68
            SimpleContent::class,
69
            TemplatedContent::class,
70
        ];
71
    }
72
73
    protected function supportsContent(Content $content): bool
74
    {
75
        foreach ($this->supportedContent() as $contentType) {
76
            if ($content instanceof $contentType) {
77
                return true;
78
            }
79
        }
80
81
        return false;
82
    }
83
84
    protected function prepareEmail(Email $email): array
85
    {
86
        $preparedEmail = [
87
            'Messages' => [
88
                array_merge([
89
                    'CustomID' => Uuid::uuid4()->toString(),
90
                    'From' => $this->buildAddress($email->getFrom()),
91
                    'To' => $this->buildAddresses($email->getToRecipients()),
92
                    'Cc' => $this->buildAddresses($email->getCcRecipients()),
93
                    'Bcc' => $this->buildAddresses($email->getBccRecipients()),
94
                    'Subject' => substr($email->getSubject(), 0, 255),
95
                    'Attachments' => $this->buildAttachments($email->getAttachments(), false),
96
                    'InlinedAttachments' => $this->buildAttachments($email->getEmbedded(), true),
97
                ], $this->buildContent($email)),
98
            ],
99
        ];
100
101
        if (!empty($email->getReplyTos())) {
102
            $replyTos = $email->getReplyTos();
103
            $replyTo = $this->buildAddress(reset($replyTos));
104
105
            $preparedEmail['Messages'][0]['ReplyTo'] = $replyTo;
106
        }
107
108
        if (!empty($email->getHeaders())) {
109
            $preparedEmail['Messages'][0]['Headers'] = $this->buildHeaders($email->getHeaders());
1 ignored issue
show
Bug introduced by
Are you sure the assignment to $preparedEmail['Messages'][0]['Headers'] is correct as $this->buildHeaders($email->getHeaders()) targeting Camuthig\Courier\Mailjet...Courier::buildHeaders() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
110
        }
111
112
        return $preparedEmail;
113
    }
114
115
    protected function buildContent(Email $email): array
116
    {
117
        $content = $email->getContent();
118
119
        if ($content instanceof TemplatedContent) {
120
            return [
121
                'TemplateID' => (int) $content->getTemplateId(),
122
                'Variables' => $content->getTemplateData(),
123
            ];
124
        } elseif ($content instanceof SimpleContent) {
125
            return [
126
                'TextPart' => $content->getText()->getBody(),
127
                'HTMLPart' => $content->getHtml()->getBody(),
128
            ];
129
        }
130
131
        return [
132
            'TextPart' => '',
133
            'HTMLPart' => '',
134
        ];
135
    }
136
137
    protected function buildAddresses(array $addresses): array
138
    {
139
        return array_map(function (Address $address) {
140
            return $this->buildAddress($address);
141
        }, $addresses);
142
    }
143
144
    protected function buildAddress(Address $address): array
145
    {
146
        return [
147
            'Email' => $address->getEmail(),
148
            'Name' => $address->getName() ?? 'null',
149
        ];
150
    }
151
152
    protected function buildAttachments(array $attachments, bool $embedded): array
153
    {
154
        return array_map(function (Attachment $attachment) use ($embedded) {
155
            $arr = [
156
                'ContentType' => $attachment->getContentType(),
157
                'Filename' => $attachment->getName(),
158
                'Base64Content' => $attachment->getBase64Content(),
159
            ];
160
161
            if ($embedded) {
162
                $arr['ContentID'] = $attachment->getContentId();
163
            }
164
165
            return $arr;
166
        }, $attachments);
167
    }
168
169
    /**
170
     * @param Header[] $headers
171
     *
172
     * @return array|null
173
     */
174
    protected function buildHeaders(array $headers): ?array
175
    {
176
        $headersArray = [];
177
178
        foreach ($headers as $header) {
179
            $headersArray[$header->getField()] = $header->getValue();
180
        }
181
182
        if (empty($headersArray)) {
183
            return null;
184
        }
185
186
        return $headersArray;
187
    }
188
}
189