Mailer::sendMessage()   F
last analyzed

Complexity

Conditions 17
Paths 3330

Size

Total Lines 89
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 17
eloc 61
c 2
b 0
f 0
nc 3330
nop 1
dl 0
loc 89
rs 1.0499

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
 * Mail.php
4
 *
5
 * PHP version 8.1+
6
 *
7
 * @author Manuel Avelar <[email protected]>
8
 * @copyright 2024 Manuel Avelar
9
 * @license http://pixelcreart.com/license license
10
 * @version 1.0.0
11
 * @link http://www.pixelcreart.com
12
 * @package pixelcreart\sendgrid
13
 */
14
15
namespace pixelcreart\sendgrid;
16
17
use Exception;
18
use InvalidArgumentException;
19
use SendGrid;
20
use SendGrid\Mail\Mail;
21
use Yii;
22
use yii\base\InvalidConfigException;
23
use yii\mail\BaseMailer;
24
25
/**
26
 * This component allow user to send an email
27
 *
28
 * @author Manuel Avelar <[email protected]>
29
 * @copyright 2024 Manuel Avelar
30
 * @license http://www.pixelcreart.com/license license
31
 * @version 1.0.0
32
 * @link http://www.pixelcreart.com
33
 * @package pixelcreart\sendgrid
34
 * @since 1.0.0
35
 * @todo implement batch messages using API
36
 */
37
class Mailer extends BaseMailer
38
{
39
    /**
40
     * @var string Sendgrid API Key
41
     */
42
    public $token;
43
44
    /**
45
     * @var array options as defined in https://github.com/sendgrid/sendgrid-php#usage
46
     */
47
    public $options;
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public $messageClass = 'pixelcreart\sendgrid\Message';
53
    /**
54
     * @param Message $message
55
     * @since 1.0.0
56
     * @throws InvalidConfigException
57
     */
58
    public function sendMessage($message)
59
    {
60
        try {
61
            if (($this->token === null)) {
62
                throw new InvalidConfigException('Token or login/password are missing');
63
            }
64
            $client = null;
65
            if ($this->token !== null) {
66
                $client = new SendGrid($this->token, $this->options);
67
            }
68
            if ($client === null) {
69
                throw new InvalidArgumentException('Email transport must be configured');
70
            }
71
            $sendGridMail = new Mail();
72
            $replyTo = $message->getReplyTo();
73
            if ($replyTo !== null) {
0 ignored issues
show
introduced by
The condition $replyTo !== null is always true.
Loading history...
74
                $sendGridMail->setReplyTo($replyTo);
75
            }
76
            $sendGridMail->setFrom($message->getFrom(), $message->getFromName());
77
            
78
            foreach($message->getTo() as $email => $name) {
79
                $sendGridMail->addTo($email, $name);
80
            }
81
            foreach($message->getCc() as $email => $name) {
82
                $sendGridMail->addCc($email, $name);
83
            }
84
            foreach($message->getBcc() as $email => $name) {
85
                $sendGridMail->addBcc($email, $name);
86
            }
87
            $sendGridMail->setSubject($message->getSubject());
88
            foreach($message->getHeaders() as $header) {
89
                foreach($header as $key => $value) {
90
                    $sendGridMail->addHeader($key, $value);
91
                }
92
            }
93
            foreach($message->getAttachments() as $attachment) {
94
                $cid = isset($attachment['ContentID']) ? $attachment['ContentID'] : null;
95
                $sendGridMail->addAttachment($attachment['File'], $attachment['Name'], $cid);
96
            }
97
98
            $templateId = $message->getTemplateId();
99
100
            if ($templateId === null) {
0 ignored issues
show
introduced by
The condition $templateId === null is always false.
Loading history...
101
                $data = $message->getHtmlBody();
102
                if ($data !== null) {
103
                    $sendGridMail->addContent('text/html',$data);
104
                }
105
                $data = $message->getTextBody();
106
                if ($data !== null) {
107
                    $sendGridMail->addContent('text/plain',$data);
108
                }
109
            } else {
110
                $sendGridMail->setTemplateId($templateId);
111
                
112
                // trigger html template
113
                $sendGridMail->addContent('text/html',' ');
114
                // trigger text template
115
                $sendGridMail->addContent('text/plain',' ');
116
                $templateModel = $message->getTemplateModel();
117
118
                if (empty($templateModel) === false) {
119
                    $sendGridMail->addDynamicTemplateDatas($templateModel);
120
                }
121
            }
122
123
            $result = $client->send($sendGridMail);
124
            /* @var \SendGrid\Response $result */
125
126
            return [
127
                'success' => $result->statusCode()==202,
128
                'statusCode' => $result->statusCode(),
129
                'body' => json_decode($result->body()),
0 ignored issues
show
Bug introduced by
The method body() does not exist on SendGrid\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

129
                'body' => json_decode($result->/** @scrutinizer ignore-call */ body()),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
130
                'headers' => $result->headers(),
131
                'params' => [
132
                    'from' => $message->getFrom(),
133
                    'to' => $message->getTo(),
134
                    'cc' => $message->getCc(),
135
                    'bcc' => $message->getBcc(),
136
                    'subject' => $message->getSubject(),
137
                    'replyTo' => $message->getReplyTo(),
138
                    'templateId' => $message->getTemplateId(),
139
                    'templateModel' => $message->getTemplateModel(),
140
                    'attachments' => $message->getAttachments(),
141
                    'headers' => $message->getHeaders(),
142
                ],
143
            ];
144
        } catch (Exception $e) {
145
            Yii::error($e->getMessage(), __METHOD__);
146
            throw $e;
147
        }
148
    }
149
}