Completed
Push — master ( 3e3b4d...dcc574 )
by Gabriel
02:53
created

Mailjet::mapEmails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Omnimail;
4
5
use Omnimail\Exception\InvalidRequestException;
6
use Psr\Log\LoggerInterface;
7
use Mailjet\Resources;
8
use Mailjet\Client;
9
10
class Mailjet implements EmailSenderInterface
11
{
12
    private $apikey;
13
    private $apisecret;
14
    private $logger;
15
    private $mailjet;
16
17
    /**
18
     * @param string $apikey
19
     * @param string $apisecret
20
     * @param LoggerInterface|null $logger
21
     */
22
    public function __construct($apikey, $apisecret, LoggerInterface $logger = null)
23
    {
24
        $this->apikey = $apikey;
25
        $this->apisecret = $apisecret;
26
        $this->logger = $logger;
27
        $this->mailjet = new Client($apikey, $apisecret);
28
    }
29
30
    public function send(EmailInterface $email)
31
    {
32
        $from = $email->getFrom();
33
34
        $body = [
35
            'FromEmail' => $from['email'],
36
            'Subject' => $email->getSubject(),
37
            'To' => $this->mapEmails($email->getTo())
38
        ];
39
40
        if (!empty($from['name'])) {
41
            $body['FromName'] = $from['name'];
42
        }
43
44
        if ($email->getReplyTo()) {
45
            $body['Headers'] = [
46
                'Reply-To' => $this->mapEmailsString($email->getReplyTo())
47
            ];
48
        }
49
50
        if ($email->getCc()) {
51
            $body['Cc'] = $this->mapEmails($email->getCc());
52
        }
53
54
        if ($email->getBcc()) {
55
            $body['Bcc'] = $this->mapEmails($email->getBcc());
56
        }
57
58
        if ($email->getTextBody()) {
59
            $body['Text-part'] = $email->getTextBody();
60
        }
61
62
        if ($email->getHtmlBody()) {
63
            $body['Html-part'] = $email->getHtmlBody();
64
        }
65
66
        if ($email->getAttachements()) {
67
            $attachements = [];
68
            foreach ($email->getAttachements() as $attachement) {
69
                $item = [
70
                    'Content-type' => $attachement->getMimeType(),
71
                    'Filename' => $attachement->getName()
72
                ];
73
                if (!$attachement->getPath() && $attachement->getContent()) {
74
                    $item['content'] = base64_encode($attachement->getContent());
75
                } elseif ($attachement->getPath()) {
76
                    $item['content'] = base64_encode(file_get_contents($attachement->getPath()));
77
                }
78
                $attachements[] = $item;
79
            }
80
            $body['Attachments'] = $attachements;
81
        }
82
83
        $response = $this->mailjet->post(Resources::$Email, ['body' => $body]);
84
85
        if ($response->success()) {
86
            if ($this->logger) {
87
                $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...
88
            }
89
        } else {
90
            if ($this->logger) {
91
                $this->logger->error("Email error: '{$response->getReasonPhrase()}'", $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...
92
            }
93
            throw new InvalidRequestException($response->getReasonPhrase());
94
        }
95
    }
96
97
    /**
98
     * @param array $emails
99
     * @return array
100
     */
101
    private function mapEmails(array $emails)
102
    {
103
        $returnValue = [];
104
        foreach ($emails as $email) {
105
            $returnValue[] = $this->mapEmail($email);
106
        }
107
        return $returnValue;
108
    }
109
110
    /**
111
     * @param array $email
112
     * @return array
113
     */
114
    private function mapEmail(array $email)
115
    {
116
        $returnValue = ['Email' => $email['email']];
117
        if ($email['name']) {
118
            $returnValue['Name'] = $email['name'];
119
        }
120
        return $returnValue;
121
    }
122
123
    /**
124
     * @param array $emails
125
     * @return string
126
     */
127 View Code Duplication
    private function mapEmailsString(array $emails)
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...
128
    {
129
        $returnValue = '';
130
        foreach ($emails as $email) {
131
            $returnValue .= $this->mapEmailString($email) . ', ';
132
        }
133
        return $returnValue ? substr($returnValue, 0, -2) : '';
134
    }
135
136
    /**
137
     * @param array $email
138
     * @return string
139
     */
140
    private function mapEmailString(array $email)
141
    {
142
        return !empty($email['name']) ? "'{$email['name']}' <{$email['email']}>" : $email['email'];
143
    }
144
}
145