Completed
Push — 5.0 ( 0260bf...ecbd4e )
by Shingo
02:21
created

SendgridTransport::isStarted()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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