Postmark::processHeaders()   C
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 47
Code Lines 22

Duplication

Lines 3
Ratio 6.38 %

Importance

Changes 0
Metric Value
dl 3
loc 47
rs 5.7377
c 0
b 0
f 0
cc 8
eloc 22
nc 7
nop 2
1
<?php namespace nyx\notify\transports\mail\drivers;
2
3
// Internal dependencies
4
use nyx\notify\transports\mail;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, nyx\notify\transports\mail\drivers\mail.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
6
/**
7
 * Postmark Mail Driver
8
 *
9
 * @package     Nyx\Notify
10
 * @version     0.1.0
11
 * @author      Michal Chojnacki <[email protected]>
12
 * @copyright   2012-2017 Nyx Dev Team
13
 * @link        https://github.com/unyx/nyx
14
 */
15
class Postmark implements mail\interfaces\Driver
16
{
17
    /**
18
     * The traits of a Postmark Mail Driver instance.
19
     */
20
    use traits\CountsRecipients;
21
22
    /**
23
     * @var string  The API key used to authorize requests to Postmark's API.
24
     */
25
    protected $key;
26
27
    /**
28
     * @var \GuzzleHttp\ClientInterface The underlying HTTP Client instance.
29
     */
30
    protected $client;
31
32
    /**
33
     * Creates a new Postmark Mail Driver instance.
34
     *
35
     * @param   \GuzzleHttp\ClientInterface $client     The HTTP Client to use.
36
     * @param   string                      $key        The API key to be used to authorize requests to Postmark's API.
37
     */
38
    public function __construct(\GuzzleHttp\ClientInterface $client, string $key)
39
    {
40
        $this->key    = $key;
41
        $this->client = $client;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 View Code Duplication
    public function send(\Swift_Mime_Message $message, &$failures = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
48
    {
49
        $this->client->request('POST','https://api.postmarkapp.com/email', [
50
            'headers' => [
51
                'X-Postmark-Server-Token' => $this->key
52
            ],
53
            'json' => $this->messageToPayload($message),
54
        ]);
55
56
        return $this->countRecipients($message);
57
    }
58
59
    /**
60
     * Converts a MIME Message to an array payload in a structure understood by Postmark's "email" endpoint.
61
     *
62
     * @param   \Swift_Mime_Message $message    The Message to convert.
63
     * @return  array                           The resulting payload.
64
     */
65 View Code Duplication
    protected function messageToPayload(\Swift_Mime_Message $message) : array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
    {
67
        $payload = [
68
            'Subject' => $message->getSubject()
69
        ];
70
71
        $this->processHeaders($message, $payload);
72
        $this->processAddresses($message, $payload);
73
        $this->processMimeEntities($message, $payload);
74
        $this->processAttachments($message, $payload);
75
76
        return $payload;
77
    }
78
79
    /**
80
     * Processes the MIME headers of a MIME Message into the payload structure passed in by reference.
81
     *
82
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
83
     * @param   array&              $payload    A reference to the payload structure.
0 ignored issues
show
Documentation introduced by
The doc-type array& could not be parsed: Unknown type name "array&" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
84
     */
85
    protected function processHeaders(\Swift_Mime_Message $message, array &$payload)
86
    {
87
        if (!$headers = $message->getHeaders()->getAll()) {
88
            return;
89
        }
90
91
        $payload['Headers'] = [];
92
93
        /** @var \Swift_Mime_Header $header */
94
        foreach ($headers as $header) {
95
96
            // Omit headers which are handled elsewhere.
97 View Code Duplication
            if (in_array($fieldName = $header->getFieldName(), ['Subject', 'Content-Type', 'MIME-Version', 'Date', 'From', 'To'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
                continue;
99
            }
100
101
            if ($header instanceof \Swift_Mime_Headers_UnstructuredHeader || $header instanceof \Swift_Mime_Headers_OpenDKIMHeader) {
102
103
                // Special treatment for the 'X-PM-Tag' header if it's available, which we'll pass into the payload
104
                // directly.
105
                if ($fieldName === 'X-PM-Tag'){
106
                    $payload["Tag"] = $header->getValue();
107
                } else {
108
                    $payload['Headers'][] = [
109
                        "Name"  => $fieldName,
110
                        "Value" => $header->getValue()
111
                    ];
112
                }
113
114
                continue;
115
            }
116
117
            // All other headers are handled in the same fashion.
118
            $payload['Headers'][] = [
119
                "Name"  => $fieldName,
120
                "Value" => $header->getFieldBody()
121
            ];
122
123
            // @see http://developer.postmarkapp.com/developer-send-smtp.html
124
            if ($fieldName === 'Message-ID') {
125
                $payload['Headers'][] = [
126
                    "Name"  => 'X-PM-KeepID',
127
                    "Value" => 'true'
128
                ];
129
            }
130
        }
131
    }
132
133
    /**
134
     * Processes the fields containing e-mail addresses (from, to, cc, etc.) in the MIME Message into
135
     * the payload structure passed in by reference.
136
     *
137
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
138
     * @param   array&              $payload    A reference to the payload structure.
0 ignored issues
show
Documentation introduced by
The doc-type array& could not be parsed: Unknown type name "array&" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
139
     */
140
    protected function processAddresses(\Swift_Mime_Message $message, array &$payload)
141
    {
142
        $payload['From'] = $this->emailsToString($message->getFrom());
143
        $payload['To']   = $this->emailsToString($message->getTo());
144
145
        if ($cc = $message->getCc()) {
146
            $payload['Cc'] = $this->emailsToString($cc);
147
        }
148
149
        if ($bcc = $message->getBcc()) {
150
            $payload['Bcc'] = $this->emailsToString($bcc);
151
        }
152
153
        if ($replyTo = $message->getReplyTo()) {
154
            $payload['ReplyTo'] = $this->emailsToString($replyTo);
155
        }
156
    }
157
158
    /**
159
     * Converts an array of e-mail addresses into a string compliant with Postmark's API's format.
160
     *
161
     * @param   array   $emails     The e-mail addresses to convert.
162
     * @return  string
163
     */
164
    protected function emailsToString(array $emails) : string
165
    {
166
        $addresses = [];
167
168
        foreach ($emails as $email => $name) {
169
            $addresses[] = $name ? '"' . str_replace('"', '\\"', $name) . "\" <{$email}>" : $email;
170
        }
171
172
        return implode(',', $addresses);
173
    }
174
175
    /**
176
     * Processes the MIME entities in the MIME Message into the payload structure passed in by reference.
177
     *
178
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
179
     * @param   array&              $payload    A reference to the payload structure.
0 ignored issues
show
Documentation introduced by
The doc-type array& could not be parsed: Unknown type name "array&" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
180
     */
181
    protected function processMimeEntities(\Swift_Mime_Message $message, array &$payload)
182
    {
183
        switch ($message->getContentType()) {
184
            case 'text/html':
185
            case 'multipart/alternative':
186 View Code Duplication
            case 'multipart/mixed':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
                $payload['HtmlBody'] = $message->getBody();
188
189
                if ($plain = $this->getMimePart($message, 'text/plain')) {
190
                    $payload['TextBody'] = $plain->getBody();
191
                }
192
193
                break;
194
195 View Code Duplication
            default:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
                $payload['TextBody'] = $message->getBody();
197
198
                if ($html = $this->getMimePart($message, 'text/html')) {
199
                    $payload['HtmlBody'] = $html->getBody();
200
                }
201
        }
202
    }
203
204
    /**
205
     * Returns the MIME part of the specified content type contained in the given MIME message, if it's present.
206
     *
207
     * @param   \Swift_Mime_Message     $message    The MIME Message to process.
208
     * @param   string                  $mimeType   The content type the part to return must be of.
209
     * @return  \Swift_Mime_MimeEntity
210
     */
211 View Code Duplication
    protected function getMimePart(\Swift_Mime_Message $message, string $mimeType)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212
    {
213
        foreach ($message->getChildren() as $part) {
214
            if (0 === strpos($part->getContentType(), $mimeType) && !$part instanceof \Swift_Mime_Attachment) {
215
                return $part;
216
            }
217
        }
218
    }
219
220
    /**
221
     * Processes the attachments in the MIME Message into the payload structure passed in by reference.
222
     *
223
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
224
     * @param   array&              $payload    A reference to the payload structure.
0 ignored issues
show
Documentation introduced by
The doc-type array& could not be parsed: Unknown type name "array&" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
225
     */
226 View Code Duplication
    protected function processAttachments(\Swift_Mime_Message $message, array &$payload)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
227
    {
228
        if (!$children = $message->getChildren()) {
229
            return;
230
        }
231
232
        $payload['Attachments'] = [];
233
234
        foreach ($children as $attachment) {
235
236
            // Omit all entities that aren't actually attachments.
237
            if (!$attachment instanceof \Swift_Mime_Attachment) {
238
                continue;
239
            }
240
241
            $data = [
242
                'Name'        => $attachment->getFilename(),
243
                'Content'     => base64_encode($attachment->getBody()),
244
                'ContentType' => $attachment->getContentType()
245
            ];
246
247
            if ($attachment->getDisposition() !== 'attachment' && null !== $attachment->getId()) {
248
                $data['ContentID'] = 'cid:'.$attachment->getId();
249
            }
250
251
            $payload['Attachments'][] = $data;
252
        }
253
    }
254
}
255