Completed
Push — dev ( 4e6d68...cb9357 )
by Shingo
02:05
created

SendgridV3Transport::send()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 25
rs 8.8571
cc 3
eloc 15
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 $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
        $attachments = $this->getAttachments($message);
48
        if (count($attachments) > 0) {
49
            $data['attachments'] = $attachments;
50
        }
51
52
        $data = $this->setParameters($message, $data);
53
54
        $payload['json'] = $data;
55
56
        if ($this->pretend) {
57
            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...
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
        $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...
82
83
        if ($cc = $message->getCc()) {
84
            $personalizatioin['cc'] = $setter($cc);
85
        }
86
87
        if ($bcc = $message->getBcc()) {
88
            $personalizatioin['bcc'] = $setter($bcc);
89
        }
90
91
        return [$personalizatioin];
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 contents.
112
     *
113
     * @param Swift_Mime_Message $message
114
     * @return array
115
     */
116
    private function getContents(Swift_Mime_Message $message)
117
    {
118
        $content = [];
119
        foreach ($message->getChildren() as $attachment) {
120
            if ($attachment instanceof Swift_MimePart) {
121
                $content[] = [
122
                    'type'  => 'text/plain',
123
                    'value' => $attachment->getBody(),
124
                ];
125
                break;
126
            }
127
        }
128
129
        if (empty($content) || strpos($message->getContentType(), 'multipart') !== false) {
130
            $content[] = [
131
                'type'  => 'text/html',
132
                'value' => $message->getBody(),
133
            ];
134
        }
135
        return $content;
136
    }
137
138
    /**
139
     * @param Swift_Mime_Message $message
140
     * @return array
141
     */
142
    private function getAttachments(Swift_Mime_Message $message)
143
    {
144
        $attachments = [];
145
        foreach ($message->getChildren() as $attachment) {
146
            if (!$attachment instanceof Swift_Attachment || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE) {
147
                continue;
148
            }
149
            $attachments[] = [
150
                'content'     => base64_encode($attachment->getBody()),
151
                'filename'    => $attachment->getFilename(),
152
                'type'        => $attachment->getContentType(),
153
                'disposition' => $attachment->getDisposition(),
154
                'content_id'  => $attachment->getId(),
155
            ];
156
        }
157
        return $attachments;
158
    }
159
160
    /**
161
     * Set Request Body Parameters
162
     *
163
     * @param Swift_Mime_Message $message
164
     * @param array $data
165
     * @return null|string
166
     */
167
    protected function setParameters(Swift_Mime_Message $message, $data)
168
    {
169
        $smtp_api = [];
170 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...
171
            if (!$attachment instanceof Swift_Image
172
                || !in_array(self::SMTP_API_NAME, [$attachment->getFilename(), $attachment->getContentType()])
173
            ) {
174
                continue;
175
            }
176
            $smtp_api = $attachment->getBody();
177
        }
178
179
        if (!is_array($smtp_api)) {
180
            return $data;
181
        }
182
183
        foreach ($smtp_api as $key => $val) {
184
            array_set($data, $key, $val);
185
        }
186
        return $data;
187
    }
188
189
}
190