Completed
Push — master ( bd0fd2...127f89 )
by Gabriel
02:39
created

Sendgrid::mapEmail()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Omnimail;
4
5
use Omnimail\Exception\InvalidRequestException;
6
use Omnimail\Exception\UnauthorizedException;
7
use Psr\Log\LoggerInterface;
8
use SendGrid\Email;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Omnimail\Email.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
use SendGrid\Content;
10
use SendGrid\Mail;
11
use SendGrid\Attachment;
12
use SendGrid\Personalization;
13
use SendGrid\Response;
14
15
class Sendgrid implements EmailSenderInterface
16
{
17
    private $apiKey;
18
    private $logger;
19
20
    /**
21
     * @param string $apiKey
22
     * @param LoggerInterface|null $logger
23
     */
24
    public function __construct($apiKey, LoggerInterface $logger = null)
25
    {
26
        $this->apiKey = $apiKey;
27
        $this->logger = $logger;
28
    }
29
30
    public function send(EmailInterface $email)
31
    {
32
        $content = null;
33
        if ($email->getHtmlBody()) {
34
            $content = new Content("text/html", $email->getHtmlBody());
35
        } elseif ($email->getTextBody()) {
36
            $content = new Content("text/plain", $email->getTextBody());
37
        }
38
39
        $mail = new Mail(
40
            $this->mapEmail($email->getFrom()),
41
            $email->getSubject(),
42
            null,
43
            $content
44
        );
45
46
        /** @var Personalization $personalization */
47
        $personalization = $mail->personalization;
48
49
        foreach ($email->getTo() as $recipient) {
50
            $personalization->addTo($this->mapEmail($recipient));
51
        }
52
53
        if ($email->getReplyTo()) {
54
            foreach ($email->getReplyTo() as $recipient) {
55
                $mail->setReplyTo($this->mapEmail($recipient));
56
                break; // only one reply to
57
            }
58
        }
59
60
        if ($email->getCc()) {
61
            foreach ($email->getCc() as $recipient) {
62
                $personalization->addCc($this->mapEmail($recipient));
63
            }
64
        }
65
66
        if ($email->getBcc()) {
67
            foreach ($email->getBcc() as $recipient) {
68
                $personalization->addBcc($this->mapEmail($recipient));
69
            }
70
        }
71
72
        if ($email->getAttachements()) {
73
            foreach ($email->getAttachements() as $attachement) {
74
                $finalAttachment = new Attachment();
75
                $finalAttachment->setType($attachement->getMimeType());
76
                $finalAttachment->setFilename($attachement->getName());
77
                if (!$attachement->getPath() && $attachement->getContent()) {
78
                    $finalAttachment->setContent(base64_encode($attachement->getContent()));
79
                } elseif ($attachement->getPath()) {
80
                    $finalAttachment->setContent(base64_encode(file_get_contents($attachement->getPath())));
81
                }
82
                $mail->addAttachment($finalAttachment);
83
            }
84
        }
85
86
        $sg = new \SendGrid($this->apiKey);
87
        /** @var Response $response */
88
        $response = $sg->client->mail()->send()->post($mail);
89
90
        if ($response->statusCode() >= 200 && $response->statusCode() < 300) {
91
            if ($this->logger) {
92
                $this->logger->info("Email sent: '{$email->getSubject()}'", $email);
0 ignored issues
show
Documentation introduced by
$email is of type object<Omnimail\EmailInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
93
            }
94
        } else {
95
            switch ($response->statusCode()) {
96
                case 401:
97
                    if ($this->logger) {
98
                        $this->logger->info("Email error: 'unauthorized'", $email);
0 ignored issues
show
Documentation introduced by
$email is of type object<Omnimail\EmailInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
99
                    }
100
                    throw new UnauthorizedException;
101
                default:
102
                    if ($this->logger) {
103
                        $this->logger->info("Email error: 'invalid request'", $email);
0 ignored issues
show
Documentation introduced by
$email is of type object<Omnimail\EmailInterface>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
                    }
105
                    throw new InvalidRequestException;
106
            }
107
        }
108
    }
109
110
    /**
111
     * @param $email
112
     * @return Email
113
     */
114
    private function mapEmail($email)
115
    {
116
        return new Email(isset($email['name']) ? $email['name'] : null, $email['email']);
117
    }
118
}
119