Completed
Push — dev ( 1dd6a9...a72f08 )
by Shingo
04:54
created

SendgridTransport::setSmtpApi()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
rs 9.2
cc 4
eloc 6
nc 3
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 SendgridTransport extends Transport
12
{
13
    const MAXIMUM_FILE_SIZE = 7340032;
14
    const SMTP_API_NAME = 'sendgrid/x-smtpapi';
15
16
    private $client;
17
    private $options;
18
19
    public function __construct(ClientInterface $client, $api_key)
20
    {
21
        $this->client = $client;
22
        $this->options = [
23
            'headers' => ['Authorization' => 'Bearer ' . $api_key]
24
        ];
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
31
    {
32
        list($from, $fromName) = $this->getFromAddresses($message);
33
        $payload = $this->options;
34
35
        $data = [
36
            'from'     => $from,
37
            'fromname' => isset($fromName) ? $fromName : null,
38
            'subject'  => $message->getSubject(),
39
            'html'     => $message->getBody()
40
        ];
41
        $this->setTo($data, $message);
42
        $this->setCc($data, $message);
43
        $this->setBcc($data, $message);
44
        $this->setText($data, $message);
45
        $this->setAttachment($data, $message);
46
        $this->setSmtpApi($data, $message);
47
48
        if (version_compare(ClientInterface::VERSION, '6') === 1) {
49
            $payload += ['form_params' => $data];
50
        } else {
51
            $payload += ['body' => $data];
52
        }
53
54
        return $this->client->post('https://api.sendgrid.com/api/mail.send.json', $payload);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->client->po....send.json', $payload); (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...
55
    }
56
57
    /**
58
     * @param  $data
59
     * @param  Swift_Mime_Message $message
60
     */
61
    protected function setTo(&$data, Swift_Mime_Message $message)
62
    {
63
        if ($from = $message->getTo()) {
64
            $data['to'] = array_keys($from);
65
            $data['toname'] = array_values($from);
66
        }
67
    }
68
69
    /**
70
     * @param $data
71
     * @param Swift_Mime_Message $message
72
     */
73
    protected function setCc(&$data, Swift_Mime_Message $message)
74
    {
75
        if ($cc = $message->getCc()) {
76
            $data['cc'] = array_keys($cc);
77
            $data['ccname'] = array_values($cc);
78
        }
79
    }
80
81
    /**
82
     * @param $data
83
     * @param Swift_Mime_Message $message
84
     */
85
    protected function setBcc(&$data, Swift_Mime_Message $message)
86
    {
87
        if ($bcc = $message->getBcc()) {
88
            $data['bcc'] = array_keys($bcc);
89
            $data['bccname'] = array_values($bcc);
90
        }
91
    }
92
93
    /**
94
     * Get From Addresses.
95
     *
96
     * @param Swift_Mime_Message $message
97
     * @return array
98
     */
99
    protected function getFromAddresses(Swift_Mime_Message $message)
100
    {
101
        if ($message->getFrom()) {
102
            foreach ($message->getFrom() as $address => $name) {
103
                return [$address, $name];
104
            }
105
        }
106
        return [];
107
    }
108
109
    /**
110
     * Set text contents.
111
     *
112
     * @param $data
113
     * @param Swift_Mime_Message $message
114
     */
115
    protected function setText(&$data, Swift_Mime_Message $message)
116
    {
117
        foreach ($message->getChildren() as $attachment) {
118
            if (!$attachment instanceof Swift_MimePart) {
119
                continue;
120
            }
121
            $data['text'] = $attachment->getBody();
122
        }
123
    }
124
125
    /**
126
     * Set Attachment Files.
127
     *
128
     * @param $data
129
     * @param Swift_Mime_Message $message
130
     */
131
    protected function setAttachment(&$data, Swift_Mime_Message $message)
132
    {
133
        foreach ($message->getChildren() as $attachment) {
134
            if (!$attachment instanceof Swift_Attachment || !strlen($attachment->getBody()) > self::MAXIMUM_FILE_SIZE) {
135
                continue;
136
            }
137
            $handler = tmpfile();
138
            fwrite($handler, $attachment->getBody());
139
            $data['files[' . $attachment->getFilename() . ']'] = $handler;
140
        }
141
    }
142
143
    /**
144
     * Set Sendgrid SMTP API
145
     *
146
     * @param $data
147
     * @param Swift_Mime_Message $message
148
     */
149
    protected function setSmtpApi(&$data, Swift_Mime_Message $message)
150
    {
151
        foreach ($message->getChildren() as $attachment) {
152
            if (!$attachment instanceof Swift_Image
153
                || !in_array(self::SMTP_API_NAME, [$attachment->getFilename(), $attachment->getContentType()])
154
            ) {
155
                continue;
156
            }
157
            $data['x-smtpapi'] = json_encode($attachment->getBody());
158
        }
159
    }
160
}
161