Completed
Push — master ( cc8235...b61d52 )
by Sean
03:14
created

MessageBuilder::setSubject()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.3332

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 1
crap 3.3332
1
<?PHP
2
3
/*
4
 * Copyright (C) 2013-2016 Mailgun
5
 *
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Mailgun\Messages;
11
12
use Mailgun\Constants\Api;
13
use Mailgun\Constants\ExceptionMessages;
14
use Mailgun\Messages\Exceptions\InvalidParameter;
15
use Mailgun\Messages\Exceptions\TooManyParameters;
16
17
/**
18
 * This class is used for composing a properly formed
19
 * message object. Dealing with arrays can be cumbersome,
20
 * this class makes the process easier. See the official
21
 * documentation (link below) for usage instructions.
22
 *
23
 * @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Messages/README.md
24
 */
25
class MessageBuilder
26
{
27
    /**
28
     * @var array
29
     */
30
    protected $message = [];
31
32
    /**
33
     * @var array
34
     */
35
    protected $variables = [];
36
37
    /**
38
     * @var array
39
     */
40
    protected $files = [];
41
42
    /**
43
     * @var array
44
     */
45
    protected $counters = [
46
        'recipients' => [
47
            'to' => 0,
48
            'cc' => 0,
49
            'bcc' => 0,
50
        ],
51
        'attributes' => [
52
            'attachment' => 0,
53
            'campaign_id' => 0,
54
            'custom_option' => 0,
55
            'tag' => 0,
56
        ],
57
    ];
58
59
    /**
60
     * @param array  $params
61
     * @param string $key
62
     * @param mixed  $default
63
     *
64
     * @return mixed
65
     */
66 20
    protected function safeGet($params, $key, $default)
67
    {
68 20
        if (array_key_exists($key, $params)) {
69 17
            return $params[$key];
70
        }
71
72 3
        return $default;
73
    }
74
75
    /**
76
     * @param array $params
77
     *
78
     * @return mixed|string
79
     */
80 20
    protected function getFullName($params)
81
    {
82 20
        if (array_key_exists('first', $params)) {
83 17
            $first = $this->safeGet($params, 'first', '');
84 17
            $last = $this->safeGet($params, 'last', '');
85
86 17
            return trim("$first $last");
87
        }
88
89 3
        return $this->safeGet($params, 'full_name', '');
90
    }
91
92
    /**
93
     * @param string $address
94
     * @param array  $variables
95
     *
96
     * @return string
97
     */
98 20
    protected function parseAddress($address, $variables)
99
    {
100 20
        if (!is_array($variables)) {
101
            return $address;
102
        }
103 20
        $fullName = $this->getFullName($variables);
104 20
        if ($fullName != null) {
105 17
            return "'$fullName' <$address>";
106
        }
107
108 3
        return $address;
109
    }
110
111
    /**
112
     * @param string $headerName
113
     * @param string $address
114
     * @param array  $variables
115
     */
116 10
    protected function addRecipient($headerName, $address, $variables)
117
    {
118 10
        $compiledAddress = $this->parseAddress($address, $variables);
119
120 10 View Code Duplication
        if (isset($this->message[$headerName])) {
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...
121 1
            array_push($this->message[$headerName], $compiledAddress);
122 10
        } elseif ($headerName == 'h:reply-to') {
123 1
            $this->message[$headerName] = $compiledAddress;
124 1
        } else {
125 9
            $this->message[$headerName] = [$compiledAddress];
126
        }
127 10
        if (array_key_exists($headerName, $this->counters['recipients'])) {
128 8
            $this->counters['recipients'][$headerName] += 1;
129 8
        }
130 10
    }
131
132
    /**
133
     * @param string     $address
134
     * @param array|null $variables
135
     *
136
     * @throws TooManyParameters
137
     *
138
     * @return mixed
139
     */
140 12 View Code Duplication
    public function addToRecipient($address, $variables = 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...
141
    {
142 12
        if ($this->counters['recipients']['to'] > Api::RECIPIENT_COUNT_LIMIT) {
143
            throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
144
        }
145
146 12
        $variables = is_array($variables) ? $variables : [];
147
148 12
        $this->addRecipient('to', $address, $variables);
149
150 12
        return end($this->message['to']);
151
    }
152
153
    /**
154
     * @param string     $address
155
     * @param array|null $variables
156
     *
157
     * @throws TooManyParameters
158
     *
159
     * @return mixed
160
     */
161 4 View Code Duplication
    public function addCcRecipient($address, $variables = 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...
162
    {
163 4
        if ($this->counters['recipients']['cc'] > Api::RECIPIENT_COUNT_LIMIT) {
164
            throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
165
        }
166
167 4
        $variables = is_array($variables) ? $variables : [];
168
169 4
        $this->addRecipient('cc', $address, $variables);
170
171 4
        return end($this->message['cc']);
172
    }
173
174
    /**
175
     * @param string     $address
176
     * @param array|null $variables
177
     *
178
     * @throws TooManyParameters
179
     *
180
     * @return mixed
181
     */
182 4 View Code Duplication
    public function addBccRecipient($address, $variables = 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...
183
    {
184 4
        if ($this->counters['recipients']['bcc'] > Api::RECIPIENT_COUNT_LIMIT) {
185
            throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
186
        }
187
188 4
        $variables = is_array($variables) ? $variables : [];
189
190 4
        $this->addRecipient('bcc', $address, $variables);
191
192 4
        return end($this->message['bcc']);
193
    }
194
195
    /**
196
     * @param string     $address
197
     * @param array|null $variables
198
     *
199
     * @return mixed
200
     */
201 6 View Code Duplication
    public function setFromAddress($address, $variables = 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...
202
    {
203 6
        $variables = is_array($variables) ? $variables : [];
204
205 6
        $this->addRecipient('from', $address, $variables);
206
207 6
        return $this->message['from'];
208
    }
209
210
    /**
211
     * @param string     $address
212
     * @param array|null $variables
213
     *
214
     * @return mixed
215
     */
216 1 View Code Duplication
    public function setReplyToAddress($address, $variables = 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...
217
    {
218 1
        $variables = is_array($variables) ? $variables : [];
219
220 1
        $this->addRecipient('h:reply-to', $address, $variables);
221
222 1
        return $this->message['h:reply-to'];
223
    }
224
225
    /**
226
     * @param string $subject
227
     *
228
     * @return mixed
229
     */
230 6
    public function setSubject($subject = '')
231
    {
232 6
        if ($subject == null || $subject == '') {
233
            $subject = ' ';
234
        }
235 6
        $this->message['subject'] = $subject;
236
237 6
        return $this->message['subject'];
238
    }
239
240
    /**
241
     * @param string $headerName
242
     * @param mixed  $headerData
243
     *
244
     * @return mixed
245
     */
246 1
    public function addCustomHeader($headerName, $headerData)
247
    {
248 1
        if (!preg_match('/^h:/i', $headerName)) {
249 1
            $headerName = 'h:'.$headerName;
250 1
        }
251 1
        $this->message[$headerName] = [$headerData];
252
253 1
        return $this->message[$headerName];
254
    }
255
256
    /**
257
     * @param string $textBody
258
     *
259
     * @return string
260
     */
261 6
    public function setTextBody($textBody)
262
    {
263 6
        if ($textBody == null || $textBody == '') {
264
            $textBody = ' ';
265
        }
266 6
        $this->message['text'] = $textBody;
267
268 6
        return $this->message['text'];
269
    }
270
271
    /**
272
     * @param string $htmlBody
273
     *
274
     * @return string
275
     */
276 1
    public function setHtmlBody($htmlBody)
277
    {
278 1
        if ($htmlBody == null || $htmlBody == '') {
279
            $htmlBody = ' ';
280
        }
281 1
        $this->message['html'] = $htmlBody;
282
283 1
        return $this->message['html'];
284
    }
285
286
    /**
287
     * @param string      $attachmentPath
288
     * @param string|null $attachmentName
289
     *
290
     * @return bool
291
     */
292 3
    public function addAttachment($attachmentPath, $attachmentName = null)
293
    {
294 3
        if (isset($this->files['attachment'])) {
295
            $attachment = [
296 3
                'filePath' => $attachmentPath,
297 3
                'remoteName' => $attachmentName,
298 3
            ];
299 3
            array_push($this->files['attachment'], $attachment);
300 3
        } else {
301 3
            $this->files['attachment'] = [
302
                [
303 3
                    'filePath' => $attachmentPath,
304 3
                    'remoteName' => $attachmentName,
305 3
                ],
306
            ];
307
        }
308
309 3
        return true;
310
    }
311
312
    /**
313
     * @param string      $inlineImagePath
314
     * @param string|null $inlineImageName
315
     *
316
     * @throws InvalidParameter
317
     *
318
     * @return bool
319
     */
320 4
    public function addInlineImage($inlineImagePath, $inlineImageName = null)
321
    {
322 4
        if (strpos($inlineImagePath, '@') !== 0) {
323
            throw new InvalidParameter(ExceptionMessages::INVALID_PARAMETER_INLINE);
324
        }
325
326 4
        $this->files['inline'][] = [
327 4
            'filePath' => $inlineImagePath,
328 4
            'remoteName' => $inlineImageName,
329
        ];
330
331 4
        return true;
332
    }
333
334
    /**
335
     * @param bool $testMode
336
     *
337
     * @return string
338
     */
339 1 View Code Duplication
    public function setTestMode($testMode)
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...
340
    {
341 1
        if (filter_var($testMode, FILTER_VALIDATE_BOOLEAN)) {
342 1
            $testMode = 'yes';
343 1
        } else {
344 1
            $testMode = 'no';
345
        }
346 1
        $this->message['o:testmode'] = $testMode;
347
348 1
        return $this->message['o:testmode'];
349
    }
350
351
    /**
352
     * @param string|int $campaignId
353
     *
354
     * @throws TooManyParameters
355
     *
356
     * @return string|int
357
     */
358 1 View Code Duplication
    public function addCampaignId($campaignId)
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...
359
    {
360 1
        if ($this->counters['attributes']['campaign_id'] < Api::CAMPAIGN_ID_LIMIT) {
361 1
            if (isset($this->message['o:campaign'])) {
362 1
                array_push($this->message['o:campaign'], $campaignId);
363 1
            } else {
364 1
                $this->message['o:campaign'] = [$campaignId];
365
            }
366 1
            $this->counters['attributes']['campaign_id'] += 1;
367
368 1
            return $this->message['o:campaign'];
369
        } else {
370
            throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_CAMPAIGNS);
371
        }
372
    }
373
374
    /**
375
     * @param string $tag
376
     *
377
     * @throws TooManyParameters
378
     */
379 View Code Duplication
    public function addTag($tag)
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...
380
    {
381
        if ($this->counters['attributes']['tag'] < Api::TAG_LIMIT) {
382
            if (isset($this->message['o:tag'])) {
383
                array_push($this->message['o:tag'], $tag);
384
            } else {
385
                $this->message['o:tag'] = [$tag];
386
            }
387
            $this->counters['attributes']['tag'] += 1;
388
389
            return $this->message['o:tag'];
390
        } else {
391
            throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_TAGS);
392
        }
393
    }
394
395
    /**
396
     * @param bool $enabled
397
     *
398
     * @return mixed
399
     */
400 1 View Code Duplication
    public function setDkim($enabled)
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...
401
    {
402 1
        if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
403 1
            $enabled = 'yes';
404 1
        } else {
405 1
            $enabled = 'no';
406
        }
407 1
        $this->message['o:dkim'] = $enabled;
408
409 1
        return $this->message['o:dkim'];
410
    }
411
412
    /**
413
     * @param bool $enabled
414
     *
415
     * @return string
416
     */
417 1 View Code Duplication
    public function setOpenTracking($enabled)
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...
418
    {
419 1
        if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
420 1
            $enabled = 'yes';
421 1
        } else {
422 1
            $enabled = 'no';
423
        }
424 1
        $this->message['o:tracking-opens'] = $enabled;
425
426 1
        return $this->message['o:tracking-opens'];
427
    }
428
429
    /**
430
     * @param bool $enabled
431
     *
432
     * @return string
433
     */
434 1
    public function setClickTracking($enabled)
435
    {
436 1
        if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
437 1
            $enabled = 'yes';
438 1
        } elseif ($enabled == 'html') {
439
            $enabled = 'html';
440
        } else {
441 1
            $enabled = 'no';
442
        }
443 1
        $this->message['o:tracking-clicks'] = $enabled;
444
445 1
        return $this->message['o:tracking-clicks'];
446
    }
447
448
    /**
449
     * @param string      $timeDate
450
     * @param string|null $timeZone
451
     *
452
     * @return string
453
     */
454 1
    public function setDeliveryTime($timeDate, $timeZone = null)
455
    {
456 1
        if (isset($timeZone)) {
457 1
            $timeZoneObj = new \DateTimeZone("$timeZone");
458 1
        } else {
459 1
            $timeZoneObj = new \DateTimeZone(Api::DEFAULT_TIME_ZONE);
460
        }
461
462 1
        $dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
463 1
        $formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
464 1
        $this->message['o:deliverytime'] = $formattedTimeDate;
465
466 1
        return $this->message['o:deliverytime'];
467
    }
468
469
    /**
470
     * @param string $customName
471
     * @param mixed  $data
472
     */
473 1
    public function addCustomData($customName, $data)
474
    {
475 1
        $this->message['v:'.$customName] = json_encode($data);
476 1
    }
477
478
    /**
479
     * @param string $parameterName
480
     * @param mixed  $data
481
     *
482
     * @return mixed
483
     */
484 2
    public function addCustomParameter($parameterName, $data)
485
    {
486 2
        if (isset($this->message[$parameterName])) {
487 1
            array_push($this->message[$parameterName], $data);
488
489 1
            return $this->message[$parameterName];
490
        } else {
491 2
            $this->message[$parameterName] = [$data];
492
493 2
            return $this->message[$parameterName];
494
        }
495
    }
496
497
    /**
498
     * @param array $message
499
     */
500 1
    public function setMessage($message)
501
    {
502 1
        $this->message = $message;
503 1
    }
504
505
    /**
506
     * @return array
507
     */
508 29
    public function getMessage()
509
    {
510 29
        return $this->message;
511
    }
512
513
    /**
514
     * @return array
515
     */
516 6
    public function getFiles()
517
    {
518 6
        return $this->files;
519
    }
520
}
521