Completed
Pull Request — master (#1)
by Chris
01:37
created

MailjetCourier::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 2
    public function __construct(Client $client)
33
    {
34 2
        $this->client = $client;
35
    }
36
37
    /**
38
     * @param Email $email
39
     *
40
     * @throws TransmissionException
41
     * @throws UnsupportedContentException
42
     *
43
     * @return void
44
     */
45 2
    public function deliver(Email $email): void
46
    {
47 2
        $preparedEmail = $this->prepareEmail($email);
48
49 2
        $response = $this->client->post(Resources::$Email, ['body' => $preparedEmail], ['version' => 'v3.1']);
50
51 2
        if (!$response->success()) {
52
            throw new TransmissionException($response->getStatus(), new \Exception($response->getReasonPhrase()));
53
        }
54
55 2
        $customId = $response->getBody()['Messages'][0]['CustomID'];
56
57 2
        $this->saveReceipt($email, $customId);
58
    }
59
60
    protected function supportedContent(): array
61
    {
62
        return [
63
            EmptyContent::class,
64
            SimpleContent::class,
65
            TemplatedContent::class,
66
        ];
67
    }
68
69
    protected function supportsContent(Content $content): bool
70
    {
71
        foreach ($this->supportedContent() as $contentType) {
72
            if ($content instanceof $contentType) {
73
                return true;
74
            }
75
        }
76
77
        return false;
78
    }
79
80 2
    protected function prepareEmail(Email $email): array
81
    {
82
        $preparedEmail = [
83
            'Messages' => [
84 2
                array_merge([
85 2
                    'CustomID' => Uuid::uuid4()->toString(),
86 2
                    'From' => $this->buildAddress($email->getFrom()),
87 2
                    'To' => $this->buildAddresses($email->getToRecipients()),
88 2
                    'Cc' => $this->buildAddresses($email->getCcRecipients()),
89 2
                    'Bcc' => $this->buildAddresses($email->getBccRecipients()),
90 2
                    'Subject' => substr($email->getSubject(), 0, 255),
91 2
                    'Attachments' => $this->buildAttachments($email->getAttachments(), false),
92 2
                    'InlinedAttachments' => $this->buildAttachments($email->getEmbedded(), true),
93 2
                ], $this->buildContent($email)),
94
            ],
95
        ];
96
97 2
        if (!empty($email->getReplyTos())) {
98 1
            $replyTos = $email->getReplyTos();
99 1
            $replyTo = $this->buildAddress(reset($replyTos));
100
101 1
            $preparedEmail['Messages'][0]['ReplyTo'] = $replyTo;
102
        }
103
104 2
        if (!empty($email->getHeaders())) {
105 2
            $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...
106
        }
107
108 2
        return $preparedEmail;
109
    }
110
111 2
    protected function buildContent(Email $email): array
112
    {
113 2
        $content = $email->getContent();
114
115 2
        if ($content instanceof TemplatedContent) {
116
            return [
117 1
                'TemplateID' => (int) $content->getTemplateId(),
118 1
                'Variables' => $content->getTemplateData(),
119
            ];
120 1
        } elseif ($content instanceof SimpleContent) {
121
            return [
122 1
                'TextPart' => $content->getText()->getBody(),
123 1
                'HTMLPart' => $content->getHtml()->getBody(),
124
            ];
125
        }
126
127
        return [
128
            'TextPart' => '',
129
            'HTMLPart' => '',
130
        ];
131
    }
132
133 2
    protected function buildAddresses(array $addresses): array
134
    {
135
        return array_map(function (Address $address) {
136 2
            return $this->buildAddress($address);
137 2
        }, $addresses);
138
    }
139
140 2
    protected function buildAddress(Address $address): array
141
    {
142
        return [
143 2
            'Email' => $address->getEmail(),
144 2
            'Name' => $address->getName() ?? 'null',
145
        ];
146
    }
147
148 2
    protected function buildAttachments(array $attachments, bool $embedded): array
149
    {
150
        return array_map(function (Attachment $attachment) use ($embedded) {
151
            $arr = [
152 2
                'ContentType' => $attachment->getContentType(),
153 2
                'Filename' => $attachment->getName(),
154 2
                'Base64Content' => $attachment->getBase64Content(),
155
            ];
156
157 2
            if ($embedded) {
158 2
                $arr['ContentID'] = $attachment->getContentId();
159
            }
160
161 2
            return $arr;
162 2
        }, $attachments);
163
    }
164
165
    /**
166
     * @param Header[] $headers
167
     *
168
     * @return array|null
169
     */
170 2
    protected function buildHeaders(array $headers): ?array
171
    {
172 2
        $headersArray = [];
173
174 2
        foreach ($headers as $header) {
175 2
            $headersArray[$header->getField()] = $header->getValue();
176
        }
177
178 2
        if (empty($headersArray)) {
179
            return null;
180
        }
181
182 2
        return $headersArray;
183
    }
184
}
185