Completed
Push — master ( 1fa49d...63b4eb )
by Craig
11s
created

PostmarkTransport::getDisplayname()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Coconuts\Mail;
4
5
use Swift_MimePart;
6
use Swift_Attachment;
7
use Swift_Mime_SimpleMessage;
8
use GuzzleHttp\ClientInterface;
9
use Illuminate\Mail\Transport\Transport;
10
11
class PostmarkTransport extends Transport
12
{
13
    /**
14
     * Guzzle client instance.
15
     *
16
     * @var \GuzzleHttp\ClientInterface
17
     */
18
    protected $client;
19
20
    /**
21
     * The Postmark API key.
22
     *
23
     * @var string
24
     */
25
    protected $key;
26
27
    /**
28
     * The Postmark API end-point.
29
     *
30
     * @var string
31
     */
32
    protected $url = 'https://api.postmarkapp.com/email';
33
34
    /**
35
     * Create a new Postmark transport instance.
36
     *
37
     * @param \GuzzleHttp\ClientInterface $client
38
     * @param string $key
39
     *
40
     * @return void
41
     */
42 29
    public function __construct(ClientInterface $client, $key)
43
    {
44 29
        $this->key = $key;
45 29
        $this->client = $client;
46 29
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 1
    public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
52
    {
53 1
        $this->beforeSendPerformed($message);
54
55 1
        $response = $this->client->post($this->url, $this->payload($message));
56
57 1
        $message->getHeaders()->addTextHeader(
58 1
            'X-PM-Message-Id',
59 1
            $this->getMessageId($response)
60
        );
61
62 1
        $this->sendPerformed($message);
63
64 1
        return $this->numberOfRecipients($message);
65
    }
66
67
    /**
68
     * Get all attachments for the given message.
69
     *
70
     * @param \Swift_Mime_SimpleMessage $message
71
     *
72
     * @return array
73
     */
74 19
    protected function getAttachments(Swift_Mime_SimpleMessage $message)
75
    {
76 19
        return collect($message->getChildren())
77 19
            ->filter(function ($child) {
78 16
                return $child instanceof Swift_Attachment;
79 19
            })
80 19
            ->map(function ($child) {
81
                return [
82 15
                    'Name' => $child->getHeaders()->get('content-type')->getParameter('name'),
83 15
                    'Content' => base64_encode($child->getBody()),
84 15
                    'ContentType' => $child->getContentType(),
85
                ];
86 19
            })
87 19
            ->toArray();
88
    }
89
90
    /**
91
     * Format the display name.
92
     *
93
     * @param  string
94
     * @return string
95
     */
96 7
    protected function getDisplayname($value)
97
    {
98 7
        if (strpos($value, ',') !== false) {
99 1
            return '"' . $value . '"';
100
        }
101
102 6
        return $value;
103
    }
104
105
    /**
106
     * Format the contacts for the API request.
107
     *
108
     * @param string|array $contacts
109
     *
110
     * @return string
111
     */
112 19
    protected function getContacts($contacts)
113
    {
114 19
        return collect($contacts)
115 19
            ->map(function ($display, $address) {
116 14
                return $display ? $this->getDisplayname($display) . " <{$address}>" : $address;
117 19
            })
118 19
            ->values()
119 19
            ->implode(',');
120
    }
121
122
    /**
123
     * Get the message ID from the response.
124
     *
125
     * @param \GuzzleHttp\Psr7\Response $response
126
     *
127
     * @return string
128
     */
129 1
    protected function getMessageId($response)
130
    {
131 1
        return object_get(
132 1
            json_decode($response->getBody()->getContents()),
133 1
            'MessageID'
134
        );
135
    }
136
137
    /**
138
     * Get the body for the given message.
139
     *
140
     * @param \Swift_Mime_SimpleMessage $message
141
     *
142
     * @return string
143
     */
144 20
    protected function getBody(Swift_Mime_SimpleMessage $message)
145
    {
146 20
        return $message->getBody() ?: '';
147
    }
148
149
    /**
150
     * Get the text and html fields for the given message.
151
     *
152
     * @param \Swift_Mime_SimpleMessage $message
153
     *
154
     * @return array
155
     */
156 18
    protected function getHtmlAndTextBody(Swift_Mime_SimpleMessage $message)
157
    {
158 18
        $data = [];
159
160 18
        switch ($message->getContentType()) {
161 18
            case 'text/html':
162 17
            case 'multipart/related':
163 17
            case 'multipart/alternative':
164 2
                $data['HtmlBody'] = $this->getBody($message);
165 2
                break;
166
            default:
167 16
                $data['TextBody'] = $this->getBody($message);
168 16
                break;
169
        }
170
171 18
        if ($text = $this->getMimePart($message, 'text/plain')) {
172 1
            $data['TextBody'] = $text->getBody();
173
        }
174
175 18
        if ($html = $this->getMimePart($message, 'text/html')) {
176 13
            $data['HtmlBody'] = $html->getBody();
177
        }
178
179 18
        return $data;
180
    }
181
182
    /**
183
     * Get a mime part from the given message.
184
     *
185
     * @param \Swift_Mime_SimpleMessage $message
186
     * @param string $mimeType
187
     *
188
     * @return \Swift_MimePart
189
     */
190 19
    protected function getMimePart(Swift_Mime_SimpleMessage $message, $mimeType)
191
    {
192 19
        return collect($message->getChildren())
193 19
            ->filter(function ($child) {
194 16
                return $child instanceof Swift_MimePart;
195 19
            })
196 19
            ->filter(function ($child) use ($mimeType) {
197 15
                return strpos($child->getContentType(), $mimeType) === 0;
198 19
            })
199 19
            ->first();
200
    }
201
202
    /**
203
     * Get the subject for the given message.
204
     *
205
     * @param \Swift_Mime_SimpleMessage $message
206
     *
207
     * @return string
208
     */
209 20
    protected function getSubject(Swift_Mime_SimpleMessage $message)
210
    {
211 20
        return $message->getSubject() ?: '';
212
    }
213
214
    /**
215
     * Get the tag for the given message.
216
     *
217
     * @param \Swift_Mime_SimpleMessage $message
218
     *
219
     * @return string
220
     */
221 21
    protected function getTag(Swift_Mime_SimpleMessage $message)
222
    {
223 21
        return optional(
224 21
            collect($message->getHeaders()->getAll('tag'))
225 21
            ->last()
226
        )
227 21
        ->getFieldBody() ?: '';
228
    }
229
230
    /**
231
     * Get the HTTP payload for sending the Postmark message.
232
     *
233
     * @param \Swift_Mime_SimpleMessage $message
234
     *
235
     * @return array
236
     */
237 18
    protected function payload(Swift_Mime_SimpleMessage $message)
238
    {
239 18
        return collect([
240
            'headers' => [
241 18
                'Accept' => 'application/json',
242 18
                'Content-Type' => 'application/json',
243 18
                'X-Postmark-Server-Token' => $this->key,
244
            ]
245
        ])
246 18
        ->merge([
247 18
            'json' => collect([
248 18
                'Cc' => $this->getContacts($message->getCc()),
249 18
                'Bcc' => $this->getContacts($message->getBcc()),
250 18
                'Tag' => $this->getTag($message),
251 18
                'Subject' => $this->getSubject($message),
252 18
                'ReplyTo' => $this->getContacts($message->getReplyTo()),
253 18
                'Attachments' => $this->getAttachments($message),
254
            ])
255 18
            ->reject(function ($item) {
256 18
                return empty($item);
257 18
            })
258
            ->put('From', $this->getContacts($message->getFrom()))
259
            ->put('To', $this->getContacts($message->getTo()))
260
            ->merge($this->getHtmlAndTextBody($message))
261
        ])
262
        ->toArray();
263
    }
264
}
265