Completed
Push — master ( d6aa5f...0df4d6 )
by Shingo
9s
created

SendgridV3Transport::getReplyTo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
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
    private $pretend;
20
21
    public function __construct(ClientInterface $client, $api_key, $pretend = false)
22
    {
23
        $this->client = $client;
24
        $this->options = [
25
            'headers' => [
26
                'Authorization' => 'Bearer ' . $api_key,
27
                'Content-Type'  => 'application/json',
28
            ],
29
        ];
30
        $this->pretend = $pretend;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
37
    {
38
        $payload = $this->options;
39
40
        $data = [
41
            'personalizations' => $this->getPersonalizations($message),
42
            'from'             => $this->getFrom($message),
43
            'subject'          => $message->getSubject(),
44
            'content'          => $this->getContents($message),
45
        ];
46
47
        if ($reply_to = $this->getReplyTo($message)) {
48
            $data['reply_to'] = $reply_to;
49
        }
50
51
        $attachments = $this->getAttachments($message);
52
        if (count($attachments) > 0) {
53
            $data['attachments'] = $attachments;
54
        }
55
56
        $data = $this->setParameters($message, $data);
57
58
        $payload['json'] = $data;
59
60
        if ($this->pretend) {
61
            return [self::BASE_URL, $payload];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(self::BASE_URL, $payload); (array<string|array<string,array>>) is incompatible with the return type declared by the interface Swift_Transport::send of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
62
        }
63
        return $this->client->post('https://api.sendgrid.com/v3/mail/send', $payload);
64
    }
65
66
    /**
67
     * @param Swift_Mime_Message $message
68
     * @return array
69
     */
70
    private function getPersonalizations(Swift_Mime_Message $message)
71
    {
72
        $setter = function (array $addresses) {
73
            $recipients = [];
74
            foreach ($addresses as $email => $name) {
75
                $address = [];
76
                $address['email'] = $email;
77
                if ($name) {
78
                    $address['name'] = $name;
79
                }
80
                $recipients[] = $address;
81
            }
82
            return $recipients;
83
        };
84
85
        $personalizatioin['to'] = $setter($message->getTo());
0 ignored issues
show
Coding Style Comprehensibility introduced by
$personalizatioin was never initialized. Although not strictly required by PHP, it is generally a good practice to add $personalizatioin = 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...
86
87
        if ($cc = $message->getCc()) {
88
            $personalizatioin['cc'] = $setter($cc);
89
        }
90
91
        if ($bcc = $message->getBcc()) {
92
            $personalizatioin['bcc'] = $setter($bcc);
93
        }
94
95
        return [$personalizatioin];
96
    }
97
98
    /**
99
     * Get From Addresses.
100
     *
101
     * @param Swift_Mime_Message $message
102
     * @return array
103
     */
104
    private function getFrom(Swift_Mime_Message $message)
105
    {
106
        if ($message->getFrom()) {
107
            foreach ($message->getFrom() as $email => $name) {
108
                return ['email' => $email, 'name' => $name];
109
            }
110
        }
111
        return [];
112
    }
113
114
    /**
115
     * Get ReplyTo Addresses.
116
     *
117
     * @param Swift_Mime_Message $message
118
     * @return array
119
     */
120
    private function getReplyTo(Swift_Mime_Message $message)
121
    {
122
        if ($message->getReplyTo()) {
123
            foreach ($message->getReplyTo() as $email => $name) {
124
                return ['email' => $email, 'name' => $name];
125
            }
126
        }
127
        return null;
128
    }
129
130
    /**
131
     * Get contents.
132
     *
133
     * @param Swift_Mime_Message $message
134
     * @return array
135
     */
136
    private function getContents(Swift_Mime_Message $message)
137
    {
138
        $content = [];
139
        foreach ($message->getChildren() as $attachment) {
140
            if ($attachment instanceof Swift_MimePart) {
141
                $content[] = [
142
                    'type'  => 'text/plain',
143
                    'value' => $attachment->getBody(),
144
                ];
145
                break;
146
            }
147
        }
148
149
        if (empty($content) || strpos($message->getContentType(), 'multipart') !== false) {
150
            $content[] = [
151
                'type'  => 'text/html',
152
                'value' => $message->getBody(),
153
            ];
154
        }
155
        return $content;
156
    }
157
158
    /**
159
     * @param Swift_Mime_Message $message
160
     * @return array
161
     */
162
    private function getAttachments(Swift_Mime_Message $message)
163
    {
164
        $attachments = [];
165
        foreach ($message->getChildren() as $attachment) {
166
            if (!$attachment instanceof Swift_Attachment || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE) {
167
                continue;
168
            }
169
            $attachments[] = [
170
                'content'     => base64_encode($attachment->getBody()),
171
                'filename'    => $attachment->getFilename(),
172
                'type'        => $attachment->getContentType(),
173
                'disposition' => $attachment->getDisposition(),
174
                'content_id'  => $attachment->getId(),
175
            ];
176
        }
177
        return $attachments;
178
    }
179
180
    /**
181
     * Set Request Body Parameters
182
     *
183
     * @param Swift_Mime_Message $message
184
     * @param array $data
185
     * @return array
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
            if ($key === 'personalizations') {
205
                $this->setPersonalizations($data, $val);
206
                continue;
207
            }
208
            array_set($data, $key, $val);
209
        }
210
        return $data;
211
    }
212
213
    private function setPersonalizations(&$data, $personalizations)
214
    {
215
        foreach ($personalizations as $index => $params) {
216
            foreach ($params as $key => $val) {
217
                if (in_array($key, ['to', 'cc', 'bcc'])) {
218
                    array_set($data, 'personalizations.' . $index . '.' . $key, [$val]);
219
                } else {
220
                    array_set($data, 'personalizations.' . $index . '.' . $key, $val);
221
                }
222
            }
223
        }
224
    }
225
}
226