Completed
Pull Request — master (#13)
by Morven
03:08
created

Mailer::closeTempFileHandles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
3
namespace Kinglozzer\SilverStripeMailgunner;
4
5
use Debug;
6
use SS_Log;
7
use Convert;
8
use Exception;
9
use SapphireTest;
10
use Mailgun\Mailgun;
11
use Mailer as SilverstripeMailer;
12
use Mailgun\Messages\BatchMessage;
13
use Mailgun\HttpClientConfigurator;
14
use Mailgun\Messages\MessageBuilder;
15
16
class Mailer extends SilverstripeMailer
17
{
18
    /**
19
     * @var string
20
     * @config
21
     */
22
    private static $api_domain = '';
23
24
    /**
25
     * @var string
26
     * @config
27
     */
28
    private static $api_endpoint = '';
29
30
    /**
31
     * @var string
32
     * @config
33
     */
34
    private static $api_key = '';
35
36
    /**
37
     * @var boolean
38
     * @config
39
     */
40
    private static $debug = false;
41
42
    /**
43
     * An array of temporary file handles opened to store attachments
44
     * @var array
45
     */
46
    protected $tempFileHandles = [];
47
48
    /**
49
     * @var Mailgun
50
     */
51
    protected $mailgunClient;
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 12
    public function __construct()
57
    {
58 12
        $config = $this->config();
59 12
        $configurator = new HttpClientConfigurator();
60 12
        $configurator->setApiKey($config->api_key);
61 12
        $configurator->setDebug($config->debug);
62
63 12
        if ($config->api_endpoint) {
64
            $configurator->setEndpoint($config->api_endpoint);
65
        }
66
67 12
        $this->setMailgunClient(Mailgun::configure($configurator));
68 12
    }
69
70
    /**
71
     * @param Mailgun $client
72
     * @return self
73
     */
74 12
    public function setMailgunClient(Mailgun $client)
75
    {
76 12
        $this->mailgunClient = $client;
77 12
        return $this;
78
    }
79
80
    /**
81
     * @return Mailgun
82
     */
83 1
    public function getMailgunClient()
84
    {
85 1
        return $this->mailgunClient;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91 1
    public function sendPlain($to, $from, $subject, $plainContent, $attachments = [], $headers = [])
92
    {
93 1
        return $this->sendMessage($to, $from, $subject, $htmlContent = '', $plainContent, $attachments, $headers);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 1
    public function sendHTML($to, $from, $subject, $htmlContent, $attachments = [], $headers = [], $plainContent = '')
100
    {
101 1
        return $this->sendMessage($to, $from, $subject, $htmlContent, $plainContent, $attachments, $headers);
102
    }
103
104
    /**
105
     * @param string $to
106
     * @param string $from
107
     * @param string $subject
108
     * @param string $content
109
     * @param string $plainContent
110
     * @param array $attachments
111
     * @param array $headers
112
     */
113 3
    protected function sendMessage($to, $from, $subject, $content, $plainContent, $attachments, $headers)
114
    {
115 3
        $domain = $this->config()->api_domain;
116 3
        $client = $this->getMailgunClient();
117 3
        $attachments = $this->prepareAttachments($attachments);
118
119 3
        if (isset($headers['X-Mailgunner-Batch-Message'])) {
120 1
            $builder = $client->BatchMessage($domain);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::BatchMessage() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
121 1
            unset($headers['X-Mailgunner-Batch-Message']);
122 1
        } else {
123 2
            $builder = $client->MessageBuilder();
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::MessageBuilder() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
124
        }
125
126
        try {
127 3
            $this->buildMessage($builder, $to, $from, $subject, $content, $plainContent, $attachments, $headers);
128
129 3
            if ($builder instanceof BatchMessage) {
130 1
                $builder->finalize();
131 1
            } else {
132 2
                $client->sendMessage($domain, $builder->getMessage(), $builder->getFiles());
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::sendMessage() has been deprecated with message: Use Mailgun->messages()->send() instead. Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
133
            }
134 3
        } catch (Exception $e) {
135
            // Close and remove any temp files created for attachments
136 1
            $this->closeTempFileHandles();
137
            // Throwing the exception would break SilverStripe's Email API expectations, so we log
138
            // errors and show a message (which is hidden in live mode)
139 1
            SS_Log::log('Mailgun error: ' . $e->getMessage(), SS_Log::ERR);
140 1
            if (!SapphireTest::is_running_test()) {
141
                Debug::message('Mailgun error: ' . $e->getMessage());
142 1
            }
143
144 1
            return false;
145
        }
146
147 2
        $this->closeTempFileHandles();
148
149
        // This is a stupid API :(
150 2
        return [$to, $subject, $content, $headers, ''];
151
    }
152
153
    /**
154
     * @param MessageBuilder $builder
155
     * @param string $to
156
     * @param string $from
157
     * @param string $subject
158
     * @param string $content
159
     * @param string $plainContent
160
     * @param array $attachments
161
     * @param array $headers
162
     */
163 2
    protected function buildMessage(
164
        MessageBuilder $builder,
165
        $to,
166
        $from,
167
        $subject,
168
        $content,
169
        $plainContent,
170
        array $attachments,
171
        array $headers
172
    ) {
173
        // Add base info
174 2
        $parsedFrom = $this->parseAddresses($from);
175 2
        foreach ($parsedFrom as $email => $name) {
176 2
            $builder->setFromAddress($email, ['full_name' => $name]);
177 2
        }
178
179 2
        if (empty($plainContent)) {
180
            $plainContent = Convert::xml2raw($content);
181
        }
182
183 2
        $builder->setSubject($subject);
184 2
        $builder->setHtmlBody($content);
185 2
        $builder->setTextBody($plainContent);
0 ignored issues
show
Bug introduced by
It seems like $plainContent defined by \Convert::xml2raw($content) on line 180 can also be of type array; however, Mailgun\Messages\MessageBuilder::setTextBody() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
186
187
        // Add attachments
188 2
        foreach ($attachments as $attachment) {
189 2
            $builder->addAttachment($attachment['filePath'], $attachment['remoteName']);
190 2
        }
191
192
        // Parse Cc & Bcc headers out if they're set
193 2
        $ccAddresses = isset($headers['Cc']) ? $headers['Cc'] : '';
194 2
        $bccAddresses = isset($headers['Bcc']) ? $headers['Bcc'] : '';
195
196
        // We handle these ourselves, so can remove them from the list of headers
197 2
        unset($headers['Cc']);
198 2
        unset($headers['Bcc']);
199
200
        // Add remaining custom headers
201 2
        foreach ($headers as $name => $data) {
202 2
            $builder->addCustomHeader($name, $data);
203 2
        }
204
205
        // Add recipients. This is done last as the 'BatchMessage' message builder
206
        // will trigger sends for every 1000 addresses
207 2
        $to = $this->parseAddresses($to);
208 2
        foreach ($to as $email => $name) {
209 2
            $builder->addToRecipient($email, ['full_name' => $name]);
210 2
        }
211
212 2
        $ccAddresses = $this->parseAddresses($ccAddresses);
213 2
        foreach ($ccAddresses as $email => $name) {
214 2
            $builder->addCcRecipient($email, ['full_name' => $name]);
215 2
        }
216
217 2
        $bccAddresses = $this->parseAddresses($bccAddresses);
218 2
        foreach ($bccAddresses as $email => $name) {
219 2
            $builder->addBccRecipient($email, ['full_name' => $name]);
220 2
        }
221 2
    }
222
223
    /**
224
     * @todo This can't deal with mismatched quotes, or commas in names.
225
     *       E.g. "Smith, John" <[email protected]> or "John O'smith" <[email protected]>
226
     * @param string
227
     * @return array
228
     */
229 3
    protected function parseAddresses($addresses)
230
    {
231 3
        $parsed = [];
232
233 3
        $expr = '/\s*["\']?([^><,;"\']+)["\']?\s*((?:<[^><,]+>)?)\s*/';
234 3
        if (preg_match_all($expr, $addresses, $matches, PREG_SET_ORDER) > 0) {
235 3
            foreach ($matches as $result) {
236 3
                if (empty($result[2])) {
237
                    // If we couldn't parse out a name
238 3
                    $parsed[$result[1]] = '';
239 3
                } else {
240 3
                    $email = trim($result[2], '<>');
241 3
                    $parsed[$email] = trim($result[1]);
242
                }
243 3
            }
244 3
        }
245
246 3
        return $parsed;
247
    }
248
249
    /**
250
     * Prepare attachments for sending. SilverStripe extracts the content and
251
     * passes that to the mailer, so to save encoding it we just write them all
252
     * to individual files and let Mailgun deal with the rest.
253
     *
254
     * @todo Can we handle this better?
255
     * @param array $attachments
256
     * @return array
257
     */
258 2
    protected function prepareAttachments(array $attachments)
259
    {
260 2
        $prepared = [];
261
262 2
        foreach ($attachments as $attachment) {
263 2
            $tempFile = $this->writeToTempFile($attachment['contents']);
264
265 2
            $prepared[] = [
266 2
                'filePath' => $tempFile,
267 2
                'remoteName' => $attachment['filename']
268 2
            ];
269 2
        }
270
271 2
        return $prepared;
272
    }
273
274
    /**
275
     * @param string $contents
276
     * @return string
277
     */
278 2
    protected function writeToTempFile($contents)
279
    {
280 2
        $tempFile = tempnam(sys_get_temp_dir(), 'SS_MG_TMP');
281 2
        $fileHandle = fopen($tempFile, 'r+');
282 2
        fwrite($fileHandle, $contents);
283
284 2
        $this->tempFileHandles[] = [
285 2
            'handle' => $fileHandle,
286
            'path' => $tempFile
287 2
        ];
288
289 2
        return $tempFile;
290
    }
291
292
    /**
293
     * @return void
294
     */
295 1
    protected function closeTempFileHandles()
296
    {
297 1
        foreach ($this->tempFileHandles as $key => $data) {
298 1
            fclose($data['handle']);
299 1
            unlink($data['path']);
300 1
            unset($this->tempFileHandles[$key]);
301 1
        }
302 1
    }
303
}
304