Completed
Push — dev ( eab125...84b19a )
by Shingo
13:50
created

SendgridV3Transport::getAttachments()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 3
nop 1
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 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...
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