Completed
Pull Request — devel (#2)
by
unknown
38:16
created

Message::getMailJetMessage()   C

Complexity

Conditions 10
Paths 192

Size

Total Lines 73
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 73
rs 5.5072
c 0
b 0
f 0
cc 10
eloc 40
nc 192
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Message.php
4
 *
5
 * PHP version 5.6+
6
 *
7
 * @author Philippe Gaultier <[email protected]>
8
 * @copyright 2010-2017 Philippe Gaultier
9
 * @license http://www.sweelix.net/license license
10
 * @version XXX
11
 * @link http://www.sweelix.net
12
 * @package sweelix\mailjet
13
 */
14
15
namespace sweelix\mailjet;
16
17
18
use yii\base\InvalidConfigException;
19
use yii\base\InvalidParamException;
20
use yii\base\NotSupportedException;
21
use yii\helpers\ArrayHelper;
22
use yii\mail\BaseMessage;
23
use Yii;
24
use yii\mail\MailerInterface;
25
26
/**
27
 * This component allow user to send an email
28
 *
29
 * @author Philippe Gaultier <[email protected]>
30
 * @copyright 2010-2017 Philippe Gaultier
31
 * @license http://www.sweelix.net/license license
32
 * @version XXX
33
 * @link http://www.sweelix.net
34
 * @package sweelix\mailjet
35
 * @since XXX
36
 */
37
class Message extends BaseMessage
38
{
39
    /**
40
     * @var string|array from
41
     */
42
    protected $from;
43
44
    /**
45
     * @var string|array from
46
     */
47
    protected $sender;
48
49
    /**
50
     * @var array
51
     */
52
    protected $to = [];
53
54
    /**
55
     * @var string|array reply to
56
     */
57
    protected $replyTo;
58
59
    /**
60
     * @var array
61
     */
62
    protected $cc = [];
63
64
    /**
65
     * @var array
66
     */
67
    protected $bcc = [];
68
69
    /**
70
     * @var string
71
     */
72
    protected $subject;
73
74
    /**
75
     * @var string
76
     */
77
    protected $textBody;
78
79
    /**
80
     * @var string
81
     */
82
    protected $htmlBody;
83
84
    /**
85
     * @var array
86
     */
87
    protected $attachments = [];
88
89
    /**
90
     * @var string
91
     */
92
    protected $tag;
93
94
    /**
95
     * @var string
96
     */
97
    protected $trackOpens = 'account_default';
98
99
    /**
100
     * @var string
101
     */
102
    protected $trackClicks = 'account_default';
103
104
    /**
105
     * @var array
106
     */
107
    protected $headers = [];
108
109
    /**
110
     * @var integer
111
     */
112
    protected $templateId;
113
114
    /**
115
     * @var bool
116
     */
117
    protected $templateLanguage;
118
119
    /**
120
     * @var array model associated with the template
121
     */
122
    protected $templateModel = [];
123
124
    /**
125
     * @var bool
126
     */
127
    protected $inlineCss = true;
128
129
    protected $charset = 'utf-8';
130
131
    /**
132
     * @inheritdoc
133
     */
134
    public function getCharset()
135
    {
136
        return $this->charset;
137
    }
138
139
    /**
140
     * @inheritdoc
141
     */
142
    public function setCharset($charset)
143
    {
144
        throw new NotSupportedException();
145
    }
146
147
    /**
148
     * @inheritdoc
149
     */
150
    public function getFrom()
151
    {
152
        return self::stringifyEmails($this->from);
153
    }
154
155
    /**
156
     * @inheritdoc
157
     */
158
    public function setFrom($from)
159
    {
160
        $this->from = $from;
161
        return $this;
162
    }
163
164
    /**
165
     * @return array|string
166
     * @since XXX
167
     */
168
    public function getSender()
169
    {
170
        return $this->sender;
171
    }
172
173
    /**
174
     * @param string|array $sender
175
     * @return $this
176
     * @since XXX
177
     */
178
    public function setSender($sender)
179
    {
180
        $this->sender = $sender;
181
        return $this;
182
    }
183
184
    /**
185
     * @inheritdoc
186
     */
187
    public function getTo()
188
    {
189
        return $this->to;
190
    }
191
192
    /**
193
     * @inheritdoc
194
     */
195
    public function setTo($to)
196
    {
197
        if (is_string($to) === true) {
198
            $to = [$to];
199
        }
200
        $this->to = $to;
201
        return $this;
202
    }
203
204
    /**
205
     * @inheritdoc
206
     */
207
    public function getReplyTo()
208
    {
209
        return self::stringifyEmails($this->replyTo);
210
    }
211
212
    /**
213
     * @inheritdoc
214
     */
215
    public function setReplyTo($replyTo)
216
    {
217
        $this->replyTo = $replyTo;
218
        return $this;
219
    }
220
221
    /**
222
     * @inheritdoc
223
     */
224
    public function getCc()
225
    {
226
        return $this->cc;
227
    }
228
229
    /**
230
     * @inheritdoc
231
     */
232
    public function setCc($cc)
233
    {
234
        if (is_string($cc) === true) {
235
            $cc = [$cc];
236
        }
237
        $this->cc = $cc;
238
        return $this;
239
    }
240
241
    /**
242
     * @inheritdoc
243
     */
244
    public function getBcc()
245
    {
246
        return $this->bcc;
247
    }
248
249
    /**
250
     * @inheritdoc
251
     */
252
    public function setBcc($bcc)
253
    {
254
        if (is_string($bcc) === true) {
255
            $bcc = [$bcc];
256
        }
257
        $this->bcc = $bcc;
258
        return $this;
259
    }
260
261
    /**
262
     * @inheritdoc
263
     */
264
    public function getSubject()
265
    {
266
        return $this->subject;
267
    }
268
269
    /**
270
     * @inheritdoc
271
     */
272
    public function setSubject($subject)
273
    {
274
        $this->subject = $subject;
275
        return $this;
276
    }
277
278
    /**
279
     * @return string|null text body of the message
280
     * @since XXX
281
     */
282
    public function getTextBody()
283
    {
284
        return $this->textBody;
285
    }
286
287
    /**
288
     * @inheritdoc
289
     */
290
    public function setTextBody($text)
291
    {
292
        $this->textBody = $text;
293
        return $this;
294
    }
295
296
    /**
297
     * @return string|null html body of the message
298
     * @since XXX
299
     */
300
    public function getHtmlBody()
301
    {
302
        return $this->htmlBody;
303
    }
304
305
    /**
306
     * @inheritdoc
307
     */
308
    public function setHtmlBody($html)
309
    {
310
        $this->htmlBody = $html;
311
        return $this;
312
    }
313
314
    /**
315
     * @return string tag associated to the email
316
     * @since XXX
317
     */
318
    public function getTag()
319
    {
320
        return $this->tag;
321
    }
322
323
    /**
324
     * @param string $tag tag which should be associated to the email
325
     * @return $this
326
     * @since XXX
327
     */
328
    public function setTag($tag)
329
    {
330
        $this->tag = $tag;
331
        return $this;
332
    }
333
334
    /**
335
     * @param string $trackOpens can be account_default, disabled, enabled
336
     * @return $this
337
     * @since XXX
338
     */
339
    public function setTrackOpens($trackOpens)
340
    {
341
        $this->trackOpens = $trackOpens;
342
        return $this;
343
    }
344
345
    /**
346
     * @return string tracking status
347
     * @since XXX
348
     */
349
    public function getTrackOpens()
350
    {
351
        return $this->trackOpens;
352
    }
353
354
    /**
355
     * @param string $trackClicks can be account_default, disabled, enabled
356
     * @return $this
357
     * @since XXX
358
     */
359
    public function setTrackClicks($trackClicks)
360
    {
361
        $this->trackClicks = $trackClicks;
362
        return $this;
363
    }
364
365
    /**
366
     * @return string tracking status
367
     * @since XXX
368
     */
369
    public function getTrackClicks()
370
    {
371
        return $this->trackClicks;
372
    }
373
374
    /**
375
     * @param integer $templateId template Id used. in this case, Subject / HtmlBody / TextBody are discarded
376
     * @return $this
377
     * @since XXX
378
     */
379
    public function setTemplateId($templateId)
380
    {
381
        $this->templateId = $templateId;
382
        return $this;
383
    }
384
385
    /**
386
     * @return integer|null current templateId
387
     * @since XXX
388
     */
389
    public function getTemplateId()
390
    {
391
        return $this->templateId;
392
    }
393
394
    /**
395
     * @param integer $templateId template Id used. in this case, Subject / HtmlBody / TextBody are discarded
0 ignored issues
show
Bug introduced by
There is no parameter named $templateId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
396
     * @return $this
397
     * @since XXX
398
     */
399
    public function setTemplateLanguage($processLanguage)
400
    {
401
        $this->templateLanguage = $processLanguage;
402
        return $this;
403
    }
404
405
    /**
406
     * @return integer|null current templateId
407
     * @since XXX
408
     */
409
    public function getTemplateLanguage()
410
    {
411
        return $this->templateLanguage;
412
    }
413
    /**
414
     * @param array $templateModel model associated with the template
415
     * @return $this
416
     * @since XXX
417
     */
418
    public function setTemplateModel($templateModel)
419
    {
420
        $this->templateModel = $templateModel;
421
        if (empty($this->templateModel) === false) {
422
            $this->templateLanguage = true;
423
        }
424
        return $this;
425
    }
426
427
    /**
428
     * @return array current template model
429
     * @since XXX
430
     */
431
    public function getTemplateModel()
432
    {
433
        return $this->templateModel;
434
    }
435
436
    /**
437
     * @param bool $inlineCss define if css should be inlined
438
     * @return $this
439
     * @since XXX
440
     */
441
    public function setInlineCss($inlineCss)
442
    {
443
        $this->inlineCss = $inlineCss;
444
        return $this;
445
    }
446
447
    /**
448
     * @return bool define if css should be inlined
449
     * @since XXX
450
     */
451
    public function getInlineCss()
452
    {
453
        return $this->inlineCss;
454
    }
455
456
    /**
457
     * @param string $headerName
458
     * @param string $headerValue
459
     * @since XXX
460
     */
461
    public function addHeader($headerName, $headerValue)
462
    {
463
        $this->headers[$headerName] = $headerValue;
464
    }
465
466
    /**
467
     * @return array|null headers which should be added to the mail
468
     * @since XXX
469
     */
470
    public function getHeaders()
471
    {
472
        return empty($this->headers) ? [] : $this->headers;
473
    }
474
475
    /**
476
     * @return array|null list of attachments
477
     * @since XXX
478
     */
479
    public function getAttachments()
480
    {
481
        if (empty($this->attachments) === true) {
482
            return null;
483
        } else {
484
            $attachments = array_map(function($attachment) {
485
                $item = [
486
                    'ContentType' => $attachment['ContentType'],
487
                    'Filename' => $attachment['Name'],
488
                    'Base64Content' => $attachment['Content'],
489
                ];
490
                if (isset($attachment['ContentID']) === true) {
491
                    $item['ContentID'] = $attachment['ContentID'];
492
                }
493
                return $item;
494
            }, $this->attachments);
495
            return $attachments;
496
        }
497
    }
498
499
    /**
500
     * @inheritdoc
501
     */
502
    public function attach($fileName, array $options = [])
503
    {
504
        $attachment = [
505
            'Content' => base64_encode(file_get_contents($fileName))
506
        ];
507
        if (!empty($options['fileName'])) {
508
            $attachment['Name'] = $options['fileName'];
509
        } else {
510
            $attachment['Name'] = pathinfo($fileName, PATHINFO_BASENAME);
511
        }
512
        if (!empty($options['contentType'])) {
513
            $attachment['ContentType'] = $options['contentType'];
514
        } else {
515
            $attachment['ContentType'] = 'application/octet-stream';
516
        }
517
        $this->attachments[] = $attachment;
518
        return $this;
519
    }
520
521
    /**
522
     * @inheritdoc
523
     */
524
    public function attachContent($content, array $options = [])
525
    {
526
        $attachment = [
527
            'Content' => base64_encode($content)
528
        ];
529
        if (!empty($options['fileName'])) {
530
            $attachment['Name'] = $options['fileName'];
531
        } else {
532
            throw new InvalidParamException('Filename is missing');
533
        }
534
        if (!empty($options['contentType'])) {
535
            $attachment['ContentType'] = $options['contentType'];
536
        } else {
537
            $attachment['ContentType'] = 'application/octet-stream';
538
        }
539
        $this->attachments[] = $attachment;
540
        return $this;
541
    }
542
543
    /**
544
     * @inheritdoc
545
     */
546
    public function embed($fileName, array $options = [])
547
    {
548
        $embed = [
549
            'Content' => base64_encode(file_get_contents($fileName))
550
        ];
551
        if (!empty($options['fileName'])) {
552
            $embed['Name'] = $options['fileName'];
553
        } else {
554
            $embed['Name'] = pathinfo($fileName, PATHINFO_BASENAME);
555
        }
556
        if (!empty($options['contentType'])) {
557
            $embed['ContentType'] = $options['contentType'];
558
        } else {
559
            $embed['ContentType'] = 'application/octet-stream';
560
        }
561
        $embed['ContentID'] = 'cid:' . uniqid();
562
        $this->attachments[] = $embed;
563
        return $embed['ContentID'];
564
    }
565
566
    /**
567
     * @inheritdoc
568
     */
569
    public function embedContent($content, array $options = [])
570
    {
571
        $embed = [
572
            'Content' => base64_encode($content)
573
        ];
574
        if (!empty($options['fileName'])) {
575
            $embed['Name'] = $options['fileName'];
576
        } else {
577
            throw new InvalidParamException('Filename is missing');
578
        }
579
        if (!empty($options['contentType'])) {
580
            $embed['ContentType'] = $options['contentType'];
581
        } else {
582
            $embed['ContentType'] = 'application/octet-stream';
583
        }
584
        $embed['ContentID'] = 'cid:' . uniqid();
585
        $this->attachments[] = $embed;
586
        return $embed['ContentID'];
587
    }
588
589
    /**
590
     * Builds an array that represents the message as the MailJet API expects it
591
     * @return array message as array that the MailJet API expects
592
     */
593
    public function getMailJetMessage()
594
    {
595
        $fromEmails = Message::convertEmails($this->getFrom());
596
        $toEmails = Message::convertEmails($this->getTo());
597
598
        $mailJetMessage = [
599
            'From' => $fromEmails[0],
600
            'To' => $toEmails,
601
        ];
602
        /*
603
        if (isset($fromEmails[0]['Name']) === true) {
604
            $mailJetMessage['FromName'] = $fromEmails[0]['Name'];
605
        }
606
        */
607
608
        /*
609
        $sender = $this->getSender();
610
        if (empty($sender) === false) {
611
            $sender = Message::convertEmails($sender);
612
            $mailJetMessage['Sender'] = $sender[0];
613
        }
614
        */
615
616
        $cc = $this->getCc();
617
        if (empty($cc) === false) {
618
            $cc = Message::convertEmails($cc);
619
            $mailJetMessage['Cc'] = $cc;
620
        }
621
622
        $bcc = $this->getBcc();
623
        if (empty($cc) === false) {
624
            $bcc = Message::convertEmails($bcc);
625
            $mailJetMessage['Bcc'] = $bcc;
626
        }
627
628
        $attachments = $this->getAttachments();
629
        if ($attachments !== null) {
630
            $mailJetMessage['Attachments'] = $attachments;
631
        }
632
633
        $headers = $this->getHeaders();
634
        if (empty($headers) === false) {
635
            $mailJetMessage['Headers'] = $headers;
636
        }
637
        $mailJetMessage['TrackOpens'] = $this->getTrackOpens();
638
        $mailJetMessage['TrackClicks'] = $this->getTrackClicks();
639
640
        $templateModel = $this->getTemplateModel();
641
        if (empty($templateModel) === false) {
642
            $mailJetMessage['Variables'] = $templateModel;
643
        }
644
645
        $templateId = $this->getTemplateId();
646
        if ($templateId === null) {
647
            $mailJetMessage['Subject'] = $this->getSubject();
648
            $textBody = $this->getTextBody();
649
            if (empty($textBody) === false) {
650
                $mailJetMessage['TextPart'] = $textBody;
651
            }
652
            $htmlBody = $this->getHtmlBody();
653
            if (empty($htmlBody) === false) {
654
                $mailJetMessage['HTMLPart'] = $htmlBody;
655
            }
656
        } else {
657
            $mailJetMessage['TemplateID'] = $templateId;
658
            $processLanguage = $this->getTemplateLanguage();
659
            if ($processLanguage === true) {
660
                $mailJetMessage['TemplateLanguage'] = $processLanguage;
661
            }
662
        }
663
664
        return $mailJetMessage;
665
    }
666
667
    /**
668
     * @inheritdoc
669
     * @todo make real serialization to make message compliant with MailjetAPI
670
     */
671
    public function toString()
672
    {
673
        return serialize($this);
674
    }
675
676
677
    /**
678
     * @param array|string $emailsData email can be defined as string. In this case no transformation is done
679
     *                                 or as an array ['[email protected]', '[email protected]' => 'Email 2']
680
     * @return string|null
681
     * @since XXX
682
     */
683
    public static function stringifyEmails($emailsData)
684
    {
685
        $emails = null;
686
        if (empty($emailsData) === false) {
687
            if (is_array($emailsData) === true) {
688
                foreach ($emailsData as $key => $email) {
689
                    if (is_int($key) === true) {
690
                        $emails[] = $email;
691
                    } else {
692
                        if (preg_match('/[.,:]/', $email) > 0) {
693
                            $email = '"'. $email .'"';
694
                        }
695
                        $emails[] = $email . ' ' . '<' . $key . '>';
696
                    }
697
                }
698
                $emails = implode(', ', $emails);
699
            } elseif (is_string($emailsData) === true) {
700
                $emails = $emailsData;
701
            }
702
        }
703
        return $emails;
704
    }
705
706
    public static function convertEmails($emailsData)
707
    {
708
        $emails = [];
709
        if (empty($emailsData) === false) {
710
            if (is_array($emailsData) === true) {
711
                foreach ($emailsData as $key => $email) {
712
                    if (is_int($key) === true) {
713
                        $emails[] = [
714
                            'Email' => $email,
715
                        ];
716
                    } else {
717
                        /*if (preg_match('/[.,:]/', $email) > 0) {
718
                            $email = '"'. $email .'"';
719
                        }*/
720
                        $emails[] = [
721
                            'Email' => $key,
722
                            'Name' => $email,
723
                        ];
724
                    }
725
                }
726
            } elseif (is_string($emailsData) === true) {
727
                // "Test, Le" <[email protected]>
728
                if (preg_match('/"([^"]+)"\s<([^>]+)>/', $emailsData, $matches) > 0) {
729
                    $emails[] = [
730
                        'Email' => $matches[2],
731
                        'Name' => $matches[1],
732
                    ];
733
                } else {
734
                    $emails[] = [
735
                        'Email' => $emailsData,
736
                    ];
737
                }
738
            }
739
        }
740
        return $emails;
741
742
    }
743
}