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

Mailgun   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 175
Duplicated Lines 25.14 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 1 Features 2
Metric Value
wmc 37
c 4
b 1
f 2
lcom 1
cbo 9
dl 44
loc 175
ccs 0
cts 108
cp 0
rs 8.6

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
F send() 0 71 18
A addTmpfile() 0 4 1
A removeTmpfiles() 0 6 2
B mapAttachments() 18 18 5
B mapInlineAttachments() 18 18 5
A mapEmails() 8 8 3
A mapEmail() 0 4 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Omnimail;
4
5
use Mailgun\Messages\MessageBuilder;
6
use Omnimail\Exception\EmailDeliveryException;
7
use Omnimail\Exception\Exception;
8
use Omnimail\Exception\InvalidRequestException;
9
use Omnimail\Exception\UnauthorizedException;
10
use Psr\Log\LoggerInterface;
11
use Mailgun\Mailgun as MailgunAPI;
12
use Http\Adapter\Guzzle6\Client;
13
14
class Mailgun implements EmailSenderInterface
15
{
16
    private $apiKey;
17
    private $domain;
18
    private $mailgun;
19
    private $logger;
20
    private $tmpfiles;
21
22
    /**
23
     * @param string $apiKey
24
     * @param string $domain
25
     * @param LoggerInterface|null $logger
26
     */
27
    public function __construct($apiKey, $domain, LoggerInterface $logger = null)
28
    {
29
        $this->apiKey = $apiKey;
30
        $this->domain = $domain;
31
        $this->logger = $logger;
32
        $this->mailgun = new MailgunAPI($this->apiKey, new Client());
33
    }
34
35
    public function send(EmailInterface $email)
36
    {
37
        try {
38
            $builder = $this->mailgun->MessageBuilder();
39
            $builder->setFromAddress($this->mapEmail($email->getFrom()));
40
41
            if ($email->getReplyTos()) {
42
                $builder->setReplyToAddress($this->mapEmails($email->getReplyTos()));
43
            }
44
45
            if ($email->getCcs()) {
46
                foreach ($email->getCcs() as $recipient) {
47
                    $builder->addCcRecipient($this->mapEmail($recipient));
48
                }
49
            }
50
51
            if ($email->getBccs()) {
52
                foreach ($email->getBccs() as $recipient) {
53
                    $builder->addBccRecipient($this->mapEmail($recipient));
54
                }
55
            }
56
57
            if ($email->getTextBody()) {
58
                $builder->setTextBody($email->getTextBody());
59
            }
60
61
            if ($email->getHtmlBody()) {
62
                $builder->setHtmlBody($email->getHtmlBody());
63
            }
64
65
            if ($email->getAttachments()) {
66
                $this->mapAttachments($email->getAttachments(), $builder);
67
                $this->mapInlineAttachments($email->getAttachments(), $builder);
68
            }
69
70
            $result = $this->mailgun->post(
71
                "{$this->domain}/messages",
72
                $builder->getMessage(),
73
                $builder->getFiles()
74
            );
75
76
            switch ($result->http_response_code) {
77
                case 200:
78
                    break;
79
                case 400:
80
                    throw new InvalidRequestException;
81
                case 401:
82
                    throw new UnauthorizedException;
83
                case 402:
84
                    throw new EmailDeliveryException;
85
                default:
86
                    throw new Exception('Unknown error', 603);
87
            }
88
89
            if ($this->logger) {
90
                $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...
91
            }
92
        } catch (Exception $e) {
93
            if ($this->logger) {
94
                $this->logger->error("Email error: '{$e->getMessage()}'", $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...
95
            }
96
            throw $e;
97
        } catch (\Exception $e) {
98
            if ($this->logger) {
99
                $this->logger->error("Email error: '{$e->getMessage()}'", $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...
100
            }
101
            throw new Exception($e->getMessage(), $e->getCode(), $e);
102
        } finally {
103
            $this->removeTmpfiles();
104
        }
105
    }
106
107
    private function addTmpfile($file)
108
    {
109
        $this->tmpfiles[] = $file;
110
    }
111
112
    private function removeTmpfiles()
113
    {
114
        foreach ($this->tmpfiles as $file) {
115
            fclose($file);
116
        }
117
    }
118
119
    /**
120
     * @param AttachmentInterface[]|array|null $attachments
121
     * @param MessageBuilder $builder
122
     * @return array|null
123
     */
124 View Code Duplication
    private function mapAttachments(array $attachments, MessageBuilder $builder)
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...
125
    {
126
        foreach ($attachments as $attachment) {
127
            if ($attachment->getContentId()) {
128
                continue;
129
            }
130
131
            if ($attachment->getPath()) {
132
                $file = $attachment->getPath();
133
            } elseif ($attachment->getContent()) {
134
                $this->addTmpfile($file = tmpfile());
135
                fwrite($file, $attachment->getContent());
136
            } else {
137
                continue;
138
            }
139
            $builder->addAttachment($file, $attachment->getName());
140
        }
141
    }
142
143
    /**
144
     * @param AttachmentInterface[]|array|null $attachments
145
     * @param MessageBuilder $builder
146
     * @return array|null
147
     */
148 View Code Duplication
    private function mapInlineAttachments(array $attachments, MessageBuilder $builder)
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...
149
    {
150
        foreach ($attachments as $attachment) {
151
            if (!$attachment->getContentId()) {
152
                continue;
153
            }
154
155
            if ($attachment->getPath()) {
156
                $file = $attachment->getPath();
157
            } elseif ($attachment->getContent()) {
158
                $this->addTmpfile($file = tmpfile());
159
                fwrite($file, $attachment->getContent());
160
            } else {
161
                continue;
162
            }
163
            $builder->addInlineImage($file, $attachment->getContentId());
164
        }
165
    }
166
167
    /**
168
     * @param array $emails
169
     * @return string
170
     */
171 View Code Duplication
    private function mapEmails(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...
172
    {
173
        $returnValue = '';
174
        foreach ($emails as $email) {
175
            $returnValue .= $this->mapEmail($email) . ', ';
176
        }
177
        return $returnValue ? substr($returnValue, 0, -2) : '';
178
    }
179
180
    /**
181
     * @param array $email
182
     * @return string
183
     */
184
    private function mapEmail(array $email)
185
    {
186
        return !empty($email['name']) ? "'{$email['name']}' <{$email['email']}>" : $email['email'];
187
    }
188
}
189