Completed
Pull Request — master (#40)
by Shingo
15:13 queued 12:54
created

SendgridV3Transport::setPersonalizations()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 2
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
    private $attachments;
20
21 View Code Duplication
    public function __construct(ClientInterface $client, $api_key)
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...
22
    {
23
        $this->client = $client;
24
        $this->options = [
25
            'headers' => [
26
                'Authorization' => 'Bearer ' . $api_key,
27
                'Content-Type'  => 'application/json',
28
            ],
29
        ];
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
36
    {
37
        $payload = $this->options;
38
39
        $data = [
40
            'personalizations' => $this->getPersonalizations($message),
41
            'from'             => $this->getFrom($message),
42
            'subject'          => $message->getSubject(),
43
            'content'          => $this->getContents($message),
44
        ];
45
46
        if ($reply_to = $this->getReplyTo($message)) {
47
            $data['reply_to'] = $reply_to;
48
        }
49
50
        $attachments = $this->getAttachments($message);
51
        if (count($attachments) > 0) {
52
            $data['attachments'] = $attachments;
53
        }
54
55
        $data = $this->setParameters($message, $data);
56
57
        $payload['json'] = $data;
58
59
        return $this->client->post('https://api.sendgrid.com/v3/mail/send', $payload);
60
    }
61
62
    /**
63
     * @param Swift_Mime_Message $message
64
     * @return array
65
     */
66
    private function getPersonalizations(Swift_Mime_Message $message)
67
    {
68
        $setter = function (array $addresses) {
69
            $recipients = [];
70
            foreach ($addresses as $email => $name) {
71
                $address = [];
72
                $address['email'] = $email;
73
                if ($name) {
74
                    $address['name'] = $name;
75
                }
76
                $recipients[] = $address;
77
            }
78
            return $recipients;
79
        };
80
81
        $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...
82
83
        if ($cc = $message->getCc()) {
84
            $personalization['cc'] = $setter($cc);
85
        }
86
87
        if ($bcc = $message->getBcc()) {
88
            $personalization['bcc'] = $setter($bcc);
89
        }
90
91
        return [$personalization];
92
    }
93
94
    /**
95
     * Get From Addresses.
96
     *
97
     * @param Swift_Mime_Message $message
98
     * @return array
99
     */
100
    private function getFrom(Swift_Mime_Message $message)
101
    {
102
        if ($message->getFrom()) {
103
            foreach ($message->getFrom() as $email => $name) {
104
                return ['email' => $email, 'name' => $name];
105
            }
106
        }
107
        return [];
108
    }
109
110
    /**
111
     * Get ReplyTo Addresses.
112
     *
113
     * @param Swift_Mime_Message $message
114
     * @return array
115
     */
116
    private function getReplyTo(Swift_Mime_Message $message)
117
    {
118
        if ($message->getReplyTo()) {
119
            foreach ($message->getReplyTo() as $email => $name) {
120
                return ['email' => $email, 'name' => $name];
121
            }
122
        }
123
        return null;
124
    }
125
126
    /**
127
     * Get contents.
128
     *
129
     * @param Swift_Mime_Message $message
130
     * @return array
131
     */
132
    private function getContents(Swift_Mime_Message $message)
133
    {
134
        $content = [];
135
        foreach ($message->getChildren() as $attachment) {
136
            if ($attachment instanceof Swift_MimePart) {
137
                $content[] = [
138
                    'type'  => 'text/plain',
139
                    'value' => $attachment->getBody(),
140
                ];
141
                break;
142
            }
143
        }
144
145
        if (empty($content) || strpos($message->getContentType(), 'multipart') !== false) {
146
            $content[] = [
147
                'type'  => 'text/html',
148
                'value' => $message->getBody(),
149
            ];
150
        }
151
        return $content;
152
    }
153
154
    /**
155
     * @param Swift_Mime_Message $message
156
     * @return array
157
     */
158
    private function getAttachments(Swift_Mime_Message $message)
159
    {
160
        $attachments = [];
161
        foreach ($message->getChildren() as $attachment) {
162
            if ((!$attachment instanceof Swift_Attachment && !$attachment instanceof Swift_Image)
163
                || $attachment->getFilename() === self::SMTP_API_NAME
164
                || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE
165
            ) {
166
                continue;
167
            }
168
            $attachments[] = [
169
                'content'     => base64_encode($attachment->getBody()),
170
                'filename'    => $attachment->getFilename(),
171
                'type'        => $attachment->getContentType(),
172
                'disposition' => $attachment->getDisposition(),
173
                'content_id'  => $attachment->getId(),
174
            ];
175
        }
176
        return $this->attachments = $attachments;
177
    }
178
179
    /**
180
     * Set Request Body Parameters
181
     *
182
     * @param Swift_Mime_Message $message
183
     * @param array $data
184
     * @return array
185
     * @throws \Exception
186
     */
187
    protected function setParameters(Swift_Mime_Message $message, $data)
188
    {
189
        $smtp_api = [];
190 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...
191
            if (!$attachment instanceof Swift_Image
192
                || !in_array(self::SMTP_API_NAME, [$attachment->getFilename(), $attachment->getContentType()])
193
            ) {
194
                continue;
195
            }
196
            $smtp_api = $attachment->getBody();
197
        }
198
199
        if (!is_array($smtp_api)) {
200
            return $data;
201
        }
202
203
        foreach ($smtp_api as $key => $val) {
204
205
            switch ($key) {
206
207
                case 'personalizations':
208
                    $this->setPersonalizations($data, $val);
209
                    continue 2;
210
211
                case 'attachments':
212
                    $val = array_merge($this->attachments, $val);
213
                    break;
214
215
                case 'unique_args':
216
                    throw new \Exception('Sendgrid v3 now uses custom_args instead of unique_args');
217
218
                case 'custom_args':
219
                    foreach ($val as $name => $value) {
220
                        if (!is_string($value)) {
221
                            throw new \Exception('Sendgrid v3 custom arguments have to be a string.');
222
                        }
223
                    }
224
                    break;
225
226
            }
227
228
            array_set($data, $key, $val);
229
        }
230
        return $data;
231
    }
232
233
    private function setPersonalizations(&$data, $personalizations)
234
    {
235
        foreach ($personalizations as $index => $params) {
236
            foreach ($params as $key => $val) {
237
                if (in_array($key, ['to', 'cc', 'bcc'])) {
238
                    array_set($data, 'personalizations.' . $index . '.' . $key, [$val]);
239
                } else {
240
                    array_set($data, 'personalizations.' . $index . '.' . $key, $val);
241
                }
242
            }
243
        }
244
    }
245
}
246