Completed
Push — master ( 63b406...02f402 )
by Craig
11s
created

PostmarkTransport::getTag()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
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 28
    public function __construct(ClientInterface $client, $key)
43
    {
44 28
        $this->key = $key;
45 28
        $this->client = $client;
46 28
    }
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 18
    protected function getAttachments(Swift_Mime_SimpleMessage $message)
75
    {
76 18
        return collect($message->getChildren())
77 18
            ->filter(function ($child) {
78 15
                return $child instanceof Swift_Attachment;
79 18
            })
80 18
            ->map(function ($child) {
81
                return [
82 14
                    'Name' => $child->getHeaders()->get('content-type')->getParameter('name'),
83 14
                    'Content' => base64_encode($child->getBody()),
84 14
                    'ContentType' => $child->getContentType(),
85
                ];
86 18
            })
87 18
            ->toArray();
88
    }
89
90
    /**
91
     * Format the contacts for the API request.
92
     *
93
     * @param string|array $contacts
94
     *
95
     * @return string
96
     */
97 18
    protected function getContacts($contacts)
98
    {
99 18
        return collect($contacts)
100 18
            ->map(function ($display, $address) {
101 13
                return $display ? $display . " <{$address}>" : $address;
102 18
            })
103 18
            ->values()
104 18
            ->implode(',');
105
    }
106
107
    /**
108
     * Get the message ID from the response.
109
     *
110
     * @param \GuzzleHttp\Psr7\Response $response
111
     *
112
     * @return string
113
     */
114 1
    protected function getMessageId($response)
115
    {
116 1
        return object_get(
117 1
            json_decode($response->getBody()->getContents()),
118 1
            'MessageID'
119
        );
120
    }
121
122
    /**
123
     * Get the body for the given message.
124
     *
125
     * @param \Swift_Mime_SimpleMessage $message
126
     *
127
     * @return string
128
     */
129 19
    protected function getBody(Swift_Mime_SimpleMessage $message)
130
    {
131 19
        return $message->getBody() ?: '';
132
    }
133
134
    /**
135
     * Get the text and html fields for the given message.
136
     *
137
     * @param \Swift_Mime_SimpleMessage $message
138
     *
139
     * @return array
140
     */
141 17
    protected function getHtmlAndTextBody(Swift_Mime_SimpleMessage $message)
142
    {
143 17
        $data = [];
144
145 17
        switch ($message->getContentType()) {
146 17
            case 'text/html':
147 16
            case 'multipart/related':
148 16
            case 'multipart/alternative':
149 2
                $data['HtmlBody'] = $this->getBody($message);
150 2
                break;
151
            default:
152 15
                $data['TextBody'] = $this->getBody($message);
153 15
                break;
154
        }
155
156 17
        if ($text = $this->getMimePart($message, 'text/plain')) {
157 1
            $data['TextBody'] = $text->getBody();
158
        }
159
160 17
        if ($html = $this->getMimePart($message, 'text/html')) {
161 12
            $data['HtmlBody'] = $html->getBody();
162
        }
163
164 17
        return $data;
165
    }
166
167
    /**
168
     * Get a mime part from the given message.
169
     *
170
     * @param \Swift_Mime_SimpleMessage $message
171
     * @param string $mimeType
172
     *
173
     * @return \Swift_MimePart
174
     */
175 18
    protected function getMimePart(Swift_Mime_SimpleMessage $message, $mimeType)
176
    {
177 18
        return collect($message->getChildren())
178 18
            ->filter(function ($child) {
179 15
                return $child instanceof Swift_MimePart;
180 18
            })
181 18
            ->filter(function ($child) use ($mimeType) {
182 14
                return strpos($child->getContentType(), $mimeType) === 0;
183 18
            })
184 18
            ->first();
185
    }
186
187
    /**
188
     * Get the subject for the given message.
189
     *
190
     * @param \Swift_Mime_SimpleMessage $message
191
     *
192
     * @return string
193
     */
194 19
    protected function getSubject(Swift_Mime_SimpleMessage $message)
195
    {
196 19
        return $message->getSubject() ?: '';
197
    }
198
199
    /**
200
     * Get the tag for the given message.
201
     *
202
     * @param \Swift_Mime_SimpleMessage $message
203
     *
204
     * @return string
205
     */
206 20
    protected function getTag(Swift_Mime_SimpleMessage $message)
207
    {
208 20
        return optional(
209 20
            collect($message->getHeaders()->getAll('tag'))
210 20
            ->last()
211
        )
212 20
        ->getFieldBody() ?: '';
213
    }
214
215
    /**
216
     * Get the HTTP payload for sending the Postmark message.
217
     *
218
     * @param \Swift_Mime_SimpleMessage $message
219
     *
220
     * @return array
221
     */
222 17
    protected function payload(Swift_Mime_SimpleMessage $message)
223
    {
224 17
        return collect([
225
            'headers' => [
226 17
                'Accept' => 'application/json',
227 17
                'Content-Type' => 'application/json',
228 17
                'X-Postmark-Server-Token' => $this->key,
229
            ]
230
        ])
231 17
        ->merge([
232 17
            'json' => collect([
233 17
                'Cc' => $this->getContacts($message->getCc()),
234 17
                'Bcc' => $this->getContacts($message->getBcc()),
235 17
                'Tag' => $this->getTag($message),
236 17
                'Subject' => $this->getSubject($message),
237 17
                'ReplyTo' => $this->getContacts($message->getReplyTo()),
238 17
                'Attachments' => $this->getAttachments($message),
239
            ])
240 17
            ->reject(function ($item) {
241 17
                return empty($item);
242 17
            })
243
            ->put('From', $this->getContacts($message->getFrom()))
244
            ->put('To', $this->getContacts($message->getTo()))
245
            ->merge($this->getHtmlAndTextBody($message))
246
        ])
247
        ->toArray();
248
    }
249
}
250