Completed
Pull Request — master (#37)
by
unknown
04:44
created

SendgridV3Transport   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 227
Duplicated Lines 3.52 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 40
lcom 1
cbo 4
dl 8
loc 227
rs 8.2608
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
B send() 0 26 3
B getPersonalizations() 0 27 5
A getFrom() 0 9 3
A getReplyTo() 0 9 3
B getContents() 0 21 5
C setParameters() 8 41 11
A setPersonalizations() 0 12 4
A __construct() 0 10 1
B getAttachments() 0 17 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SendgridV3Transport often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SendgridV3Transport, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Sichikawa\LaravelSendgridDriver\Transport;
3
4
use GuzzleHttp\ClientInterface;
5
use Illuminate\Mail\Transport\Transport;
6
use Swift_Attachment;
7
use Swift_Image;
8
use Swift_Mime_Message;
9
use Swift_MimePart;
10
11
class SendgridV3Transport extends Transport
12
{
13
    const MAXIMUM_FILE_SIZE = 7340032;
14
    const SMTP_API_NAME = 'sendgrid/x-smtpapi';
15
    const BASE_URL = 'https://api.sendgrid.com/v3/mail/send';
16
17
    private $client;
18
    private $options;
19
20
    public function __construct(ClientInterface $client, $api_key)
21
    {
22
        $this->client = $client;
23
        $this->options = [
24
            'headers' => [
25
                'Authorization' => 'Bearer ' . $api_key,
26
                'Content-Type'  => 'application/json',
27
            ],
28
        ];
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
35
    {
36
        $payload = $this->options;
37
38
        $data = [
39
            'personalizations' => $this->getPersonalizations($message),
40
            'from'             => $this->getFrom($message),
41
            'subject'          => $message->getSubject(),
42
            'content'          => $this->getContents($message),
43
        ];
44
45
        if ($reply_to = $this->getReplyTo($message)) {
46
            $data['reply_to'] = $reply_to;
47
        }
48
49
        $attachments = $this->getAttachments($message);
50
        if (count($attachments) > 0) {
51
            $data['attachments'] = $attachments;
52
        }
53
54
        $data = $this->setParameters($message, $data);
55
56
        $payload['json'] = $data;
57
58
        return $this->client->post('https://api.sendgrid.com/v3/mail/send', $payload);
59
    }
60
61
    /**
62
     * @param Swift_Mime_Message $message
63
     * @return array
64
     */
65
    private function getPersonalizations(Swift_Mime_Message $message)
66
    {
67
        $setter = function (array $addresses) {
68
            $recipients = [];
69
            foreach ($addresses as $email => $name) {
70
                $address = [];
71
                $address['email'] = $email;
72
                if ($name) {
73
                    $address['name'] = $name;
74
                }
75
                $recipients[] = $address;
76
            }
77
            return $recipients;
78
        };
79
80
        $personalization['to'] = $setter($message->getTo());
0 ignored issues
show
Coding Style Comprehensibility introduced by
$personalization was never initialized. Although not strictly required by PHP, it is generally a good practice to add $personalization = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
81
82
        if ($cc = $message->getCc()) {
83
            $personalization['cc'] = $setter($cc);
84
        }
85
86
        if ($bcc = $message->getBcc()) {
87
            $personalization['bcc'] = $setter($bcc);
88
        }
89
90
        return [$personalization];
91
    }
92
93
    /**
94
     * Get From Addresses.
95
     *
96
     * @param Swift_Mime_Message $message
97
     * @return array
98
     */
99
    private function getFrom(Swift_Mime_Message $message)
100
    {
101
        if ($message->getFrom()) {
102
            foreach ($message->getFrom() as $email => $name) {
103
                return ['email' => $email, 'name' => $name];
104
            }
105
        }
106
        return [];
107
    }
108
109
    /**
110
     * Get ReplyTo Addresses.
111
     *
112
     * @param Swift_Mime_Message $message
113
     * @return array
114
     */
115
    private function getReplyTo(Swift_Mime_Message $message)
116
    {
117
        if ($message->getReplyTo()) {
118
            foreach ($message->getReplyTo() as $email => $name) {
119
                return ['email' => $email, 'name' => $name];
120
            }
121
        }
122
        return null;
123
    }
124
125
    /**
126
     * Get contents.
127
     *
128
     * @param Swift_Mime_Message $message
129
     * @return array
130
     */
131
    private function getContents(Swift_Mime_Message $message)
132
    {
133
        $content = [];
134
        foreach ($message->getChildren() as $attachment) {
135
            if ($attachment instanceof Swift_MimePart) {
136
                $content[] = [
137
                    'type'  => 'text/plain',
138
                    'value' => $attachment->getBody(),
139
                ];
140
                break;
141
            }
142
        }
143
144
        if (empty($content) || strpos($message->getContentType(), 'multipart') !== false) {
145
            $content[] = [
146
                'type'  => 'text/html',
147
                'value' => $message->getBody(),
148
            ];
149
        }
150
        return $content;
151
    }
152
153
    /**
154
     * @param Swift_Mime_Message $message
155
     * @return array
156
     */
157
    private function getAttachments(Swift_Mime_Message $message)
158
    {
159
        $attachments = [];
160
        foreach ($message->getChildren() as $attachment) {
161
            if ((!$attachment instanceof Swift_Attachment && !$attachment instanceof Swift_Image) || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE) {
162
                continue;
163
            }
164
            $attachments[] = [
165
                'content'     => base64_encode($attachment->getBody()),
166
                'filename'    => $attachment->getFilename(),
167
                'type'        => $attachment->getContentType(),
168
                'disposition' => $attachment->getDisposition(),
169
                'content_id'  => $attachment->getId(),
170
            ];
171
        }
172
        return $attachments;
173
    }
174
175
    /**
176
     * Set Request Body Parameters
177
     *
178
     * @param Swift_Mime_Message $message
179
     * @param array $data
180
     * @return array
181
     * @throws \Exception
182
     */
183
    protected function setParameters(Swift_Mime_Message $message, $data)
184
    {
185
        $smtp_api = [];
186 View Code Duplication
        foreach ($message->getChildren() as $attachment) {
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
            if (!$attachment instanceof Swift_Image
188
                || !in_array(self::SMTP_API_NAME, [$attachment->getFilename(), $attachment->getContentType()])
189
            ) {
190
                continue;
191
            }
192
            $smtp_api = $attachment->getBody();
193
        }
194
195
        if (!is_array($smtp_api)) {
196
            return $data;
197
        }
198
199
        foreach ($smtp_api as $key => $val) {
200
201
            switch($key) {
202
203
                case 'personalizations':
204
                    $this->setPersonalizations($data, $val);
205
                    continue 2;
206
207
                case 'unique_args':
208
                    throw new \Exception('Sendgrid v3 now uses custom_args instead of unique_args');
209
210
                case 'custom_args':
211
                    foreach($val as $name => $value) {
212
                        if (!is_string($value)) {
213
                            throw new \Exception('Sendgrid v3 custom arguments have to be a string.');
214
                        }
215
                    }
216
                    break;
217
218
            }
219
220
            array_set($data, $key, $val);
221
        }
222
        return $data;
223
    }
224
225
    private function setPersonalizations(&$data, $personalizations)
226
    {
227
        foreach ($personalizations as $index => $params) {
228
            foreach ($params as $key => $val) {
229
                if (in_array($key, ['to', 'cc', 'bcc'])) {
230
                    array_set($data, 'personalizations.' . $index . '.' . $key, [$val]);
231
                } else {
232
                    array_set($data, 'personalizations.' . $index . '.' . $key, $val);
233
                }
234
            }
235
        }
236
    }
237
}
238