Completed
Push — master ( 6c2fe3...ff207a )
by Gabriel
29s
created

SendinBlue::mapInlineImages()   C

Complexity

Conditions 10
Paths 9

Size

Total Lines 24
Code Lines 15

Duplication

Lines 24
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 24
loc 24
ccs 0
cts 18
cp 0
rs 5.2164
cc 10
eloc 15
nc 9
nop 1
crap 110

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->getTos()),
31
            'cc' => $this->mapEmails($email->getCcs()),
32
            'bcc' => $this->mapEmails($email->getBccs()),
33
            'from' => $this->mapEmail($email->getFrom()),
34
            'replyto' => $this->mapEmails($email->getReplyTos()),
35
            'subject' => $email->getSubject(),
36
            'text' => $email->getTextBody(),
37
            'html' => $email->getHtmlBody(),
38
            'attachment' => $this->mapAttachments($email->getAttachments()),
39
            'inline_image' => $this->mapInlineImages($email->getAttachments())
40
        ];
41
42
        $response = $mailin->send_email($data);
43
        if ($response && $response['code'] && $response['code'] === 'success') {
44
            if ($this->logger) {
45
                $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...
46
            }
47
        } else {
48
            if (!$response || !$response['code']) {
49
                throw new Exception('Unknown exception');
50
            } else {
51
                switch ($response['code']) {
52 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...
53
                        if ($this->logger) {
54
                            $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...
55
                        }
56
                        throw new InvalidRequestException($response['message']);
57 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...
58
                        if ($this->logger) {
59
                            $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...
60
                        }
61
                        throw new InvalidRequestException($response['message']);
62
                }
63
            }
64
        }
65
    }
66
67
    /**
68
     * @param array|null $attachments
69
     * @return array|null
70
     */
71 View Code Duplication
    private function mapAttachments(array $attachments = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
72
    {
73
        if (null === $attachments || !is_array($attachments) || !count($attachments)) {
74
            return null;
75
        }
76
        $finalAttachments = [];
77
        /** @var AttachmentInterface $attachment */
78
        foreach ($attachments as $attachment) {
79
            if ($attachment->getContentId()) {
80
                continue;
81
            }
82
            
83
            $content = null;
84
            if (!$attachment->getPath() && $attachment->getContent()) {
85
                $content = base64_encode($attachment->getContent());
86
            } elseif ($attachment->getPath()) {
87
                $content = base64_encode(file_get_contents($attachment->getPath()));
88
            }
89
            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...
90
                $finalAttachments[$attachment->getName()] = $content;
91
            }
92
        }
93
        return $finalAttachments;
94
    }
95
96
    /**
97
     * @param array|null $attachments
98
     * @return array|null
99
     */
100 View Code Duplication
    private function mapInlineImages(array $attachments = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
101
    {
102
        if (null === $attachments || !is_array($attachments) || !count($attachments)) {
103
            return null;
104
        }
105
        $finalAttachments = [];
106
        /** @var AttachmentInterface $attachment */
107
        foreach ($attachments as $attachment) {
108
            if (!$attachment->getContentId()) {
109
                continue;
110
            }
111
112
            $content = null;
113
            if (!$attachment->getPath() && $attachment->getContent()) {
114
                $content = base64_encode($attachment->getContent());
115
            } elseif ($attachment->getPath()) {
116
                $content = base64_encode(file_get_contents($attachment->getPath()));
117
            }
118
            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...
119
                $finalAttachments[$attachment->getContentId()] = $content;
120
            }
121
        }
122
        return $finalAttachments;
123
    }
124
125
    /**
126
     * @param array|null $emails
127
     * @return array|null
128
     */
129
    private function mapEmails(array $emails = null)
130
    {
131
        if (null === $emails || !is_array($emails) || !count($emails)) {
132
            return null;
133
        }
134
        $finalEmails = [];
135
        foreach ($emails as $email) {
136
            $finalEmails = array_merge($finalEmails, $this->mapEmail($email));
137
        }
138
        return $finalEmails;
139
    }
140
141
    /**
142
     * @param array $email
143
     * @return array
144
     */
145
    private function mapEmail(array $email)
146
    {
147
        $finalEmail = [];
148
        if ($email['name']) {
149
            $finalEmail[$email['email']] = $email['name'];
150
        } else {
151
            $finalEmail[$email['email']] = '';
152
        }
153
        return $finalEmail;
154
    }
155
}
156