Completed
Push — master ( 15a09e...404d67 )
by Shingo
9s
created

SendgridTransport::setAttachment()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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