Completed
Push — master ( 127f89...634d7f )
by Gabriel
02:41
created

SendinBlue::send()   C

Complexity

Conditions 11
Paths 8

Size

Total Lines 40
Code Lines 29

Duplication

Lines 10
Ratio 25 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 10
loc 40
rs 5.2653
cc 11
eloc 29
nc 8
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Omnimail;
4
5
use Omnimail\Exception\Exception;
6
use Omnimail\Exception\InvalidRequestException;
7
use Psr\Log\LoggerInterface;
8
use Sendinblue\Mailin;
9
10
class SendinBlue implements EmailSenderInterface
11
{
12
    private $accessKey;
13
    private $logger;
14
15
    /**
16
     * @param string $accessKey
17
     * @param LoggerInterface|null $logger
18
     */
19
    public function __construct($accessKey, LoggerInterface $logger = null)
20
    {
21
        $this->accessKey = $accessKey;
22
        $this->logger = $logger;
23
    }
24
25
    public function send(EmailInterface $email)
26
    {
27
        $mailin = new Mailin('https://api.sendinblue.com/v2.0', $this->accessKey);
28
29
        $data = [
30
            'to' => $this->mapEmails($email->getTo()),
31
            'cc' => $this->mapEmails($email->getCc()),
32
            'bcc' => $this->mapEmails($email->getBcc()),
33
            'from' => $this->mapEmail($email->getFrom()),
34
            'replyto' => $this->mapEmails($email->getReplyTo()),
35
            'subject' => $email->getSubject(),
36
            'text' => $email->getTextBody(),
37
            'html' => $email->getHtmlBody(),
38
            'attachment' => $this->mapAttachments($email->getAttachements())
39
        ];
40
41
        $response = $mailin->send_email($data);
42
        if ($response && $response['code'] && $response['code'] === 'success') {
43
            if ($this->logger) {
44
                $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...
45
            }
46
        } else {
47
            if (!$response || !$response['code']) {
48
                throw new Exception('Unknown exception');
49
            } else {
50
                switch ($response['code']) {
51 View Code Duplication
                    case 'failure':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
                        if ($this->logger) {
53
                            $this->logger->info("Email error: '{$response['message']}'", $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...
54
                        }
55
                        throw new InvalidRequestException($response['message']);
56 View Code Duplication
                    case 'error':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
57
                        if ($this->logger) {
58
                            $this->logger->info("Email error: '{$response['message']}'", $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...
59
                        }
60
                        throw new InvalidRequestException($response['message']);
61
                }
62
            }
63
        }
64
    }
65
66
    /**
67
     * @param array|null $attachements
68
     * @return array|null
69
     */
70
    private function mapAttachments(array $attachements = null)
71
    {
72 View Code Duplication
        if (null === $attachements || !is_array($attachements) || !count($attachements)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
73
            return null;
74
        }
75
        $finalAttachements = [];
76
        foreach ($attachements as $attachement) {
77
            $content = null;
78
            if (!$attachement->getPath() && $attachement->getContent()) {
79
                $content = base64_encode($attachement->getContent());
80
            } elseif ($attachement->getPath()) {
81
                $content = base64_encode(file_get_contents($attachement->getPath()));
82
            }
83
            if ($content) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $content of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
84
                $finalAttachements[$attachement->getName()] = $content;
85
            }
86
        }
87
        return $finalAttachements;
88
    }
89
90
    /**
91
     * @param array|null $emails
92
     * @return array|null
93
     */
94
    private function mapEmails(array $emails = null)
95
    {
96
        if (null === $emails || !is_array($emails) || !count($emails)) {
97
            return null;
98
        }
99
        $finalEmails = [];
100
        foreach ($emails as $email) {
101
            $finalEmails = array_merge($finalEmails, $this->mapEmail($email));
102
        }
103
        return $finalEmails;
104
    }
105
106
    /**
107
     * @param array $email
108
     * @return array
109
     */
110
    private function mapEmail(array $email)
111
    {
112
        $finalEmail = [];
113
        if ($email['name']) {
114
            $finalEmail[$email['email']] = $email['name'];
115
        } else {
116
            $finalEmail[$email['email']] = '';
117
        }
118
        return $finalEmail;
119
    }
120
}
121