Completed
Push — 5.0 ( ecbd4e...81ab5c )
by Shingo
03:25
created

SendgridTransport::setText()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
namespace Sichikawa\LaravelSendgridDriver\Transport;
3
4
use GuzzleHttp\Client;
5
use GuzzleHttp\ClientInterface;
6
use Swift_Attachment;
7
use Swift_Events_EventListener;
8
use Swift_Image;
9
use Swift_Mime_Message;
10
use Swift_MimePart;
11
use Swift_Transport;
12
13
class SendgridTransport implements Swift_Transport
14
{
15
    const MAXIMUM_FILE_SIZE = 7340032;
16
    const SMTP_API_NAME = 'sendgrid/x-smtpapi';
17
18
    private $api_key;
19
20
    public function __construct($api_key)
21
    {
22
        $this->api_key = $api_key;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function isStarted()
29
    {
30
        return true;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function start()
37
    {
38
        return true;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function stop()
45
    {
46
        return true;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
53
    {
54
        list($from, $fromName) = $this->getFromAddresses($message);
55
56
        $data = [
57
            'from'     => $from,
58
            'fromname' => isset($fromName) ? $fromName : null,
59
            'subject'  => $message->getSubject(),
60
            'html'     => $message->getBody()
61
        ];
62
63
        $this->setTo($data, $message);
64
        $this->setCc($data, $message);
65
        $this->setBcc($data, $message);
66
        $this->setText($data, $message);
67
        $this->setAttachment($data, $message);
68
        $this->setSmtpApi($data, $message);
69
70
        $options = [
71
            'headers' => ['Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'multipart/form-data']
72
        ];
73
74
        if (version_compare(ClientInterface::VERSION, '6') === 1) {
75
            $options += ['form_params' => $data];
76
        } else {
77
            $options += ['body' => $data];
78
        }
79
80
        $client = $this->getHttpClient();
81
        return $client->post('https://api.sendgrid.com/api/mail.send.json', $options);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $client->post('ht....send.json', $options); (GuzzleHttp\Message\ResponseInterface) 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...
82
    }
83
84
    /**
85
     * @param  $data
86
     * @param  Swift_Mime_Message $message
87
     */
88
    protected function setTo(&$data, Swift_Mime_Message $message)
89
    {
90
        if ($from = $message->getTo()) {
91
            $data['to'] = array_keys($from);
92
            $data['toname'] = array_values($from);
93
        }
94
    }
95
96
    /**
97
     * @param $data
98
     * @param Swift_Mime_Message $message
99
     */
100
    protected function setCc(&$data, Swift_Mime_Message $message)
101
    {
102
        if ($cc = $message->getCc()) {
103
            $data['cc'] = array_keys($cc);
104
            $data['ccname'] = array_values($cc);
105
        }
106
    }
107
108
    /**
109
     * @param $data
110
     * @param Swift_Mime_Message $message
111
     */
112
    protected function setBcc(&$data, Swift_Mime_Message $message)
113
    {
114
        if ($bcc = $message->getBcc()) {
115
            $data['bcc'] = array_keys($bcc);
116
            $data['bccname'] = array_values($bcc);
117
        }
118
    }
119
120
    /**
121
     * Set text contents.
122
     *
123
     * @param $data
124
     * @param Swift_Mime_Message $message
125
     */
126
    protected function setText(&$data, Swift_Mime_Message $message)
127
    {
128
        foreach ($message->getChildren() as $attachment) {
129
            if (!$attachment instanceof Swift_MimePart) {
130
                continue;
131
            }
132
            $data['text'] = $attachment->getBody();
133
        }
134
    }
135
136
    /**
137
     * Set Attachment Files.
138
     *
139
     * @param $data
140
     * @param Swift_Mime_Message $message
141
     */
142
    protected function setAttachment(&$data, Swift_Mime_Message $message)
143
    {
144
        foreach ($message->getChildren() as $attachment) {
145
            if (!$attachment instanceof Swift_Attachment || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE) {
146
                continue;
147
            }
148
            $handler = tmpfile();
149
            fwrite($handler, $attachment->getBody());
150
            $data['files[' . $attachment->getFilename() . ']'] = $handler;
151
        }
152
    }
153
154
    /**
155
     * Set Sendgrid SMTP API
156
     *
157
     * @param $data
158
     * @param Swift_Mime_Message $message
159
     */
160
    protected function setSmtpApi(&$data, Swift_Mime_Message $message)
161
    {
162
        foreach ($message->getChildren() as $attachment) {
163
            if (!$attachment instanceof Swift_Image
164
                || !in_array(self::SMTP_API_NAME, [$attachment->getFilename(), $attachment->getContentType()])
165
            ) {
166
                continue;
167
            }
168
            $data['x-smtpapi'] = json_encode($attachment->getBody());
169
        }
170
    }
171
172
    /**
173
     * Get From Addresses.
174
     *
175
     * @param Swift_Mime_Message $message
176
     * @return array
177
     */
178
    protected function getFromAddresses(Swift_Mime_Message $message)
179
    {
180
        if ($message->getFrom()) {
181
            foreach ($message->getFrom() as $address => $name) {
182
                return [$address, $name];
183
            }
184
        }
185
        return [];
186
    }
187
188
    /**
189
     * Get a new HTTP client instance.
190
     *
191
     * @return \GuzzleHttp\Client
192
     */
193
    protected function getHttpClient()
194
    {
195
        return new Client;
196
    }
197
198
    /**
199
     * {@inheritdoc}
200
     */
201
    public function registerPlugin(Swift_Events_EventListener $plugin)
202
    {
203
        //
204
    }
205
}