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

Postmark::mapAttachments()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 27
ccs 0
cts 19
cp 0
rs 4.909
cc 9
eloc 16
nc 8
nop 1
crap 90
1
<?php
2
3
namespace Omnimail;
4
5
use Omnimail\Exception\EmailDeliveryException;
6
use Omnimail\Exception\Exception;
7
use Omnimail\Exception\InvalidRequestException;
8
use Omnimail\Exception\UnauthorizedException;
9
use Psr\Log\LoggerInterface;
10
use Postmark\PostmarkClient;
11
use Postmark\Models\PostmarkException;
12
13
class Postmark implements EmailSenderInterface
14
{
15
    private $serverApiToken;
16
    private $logger;
17
18
    /**
19
     * @param string $serverApiToken
20
     * @param LoggerInterface|null $logger
21
     */
22
    public function __construct($serverApiToken, LoggerInterface $logger = null)
23
    {
24
        $this->serverApiToken = $serverApiToken;
25
        $this->logger = $logger;
26
    }
27
28
    public function send(EmailInterface $email)
29
    {
30
        try {
31
            $client = new PostmarkClient($this->serverApiToken);
32
            $sendResult = $client->sendEmail(
33
                $this->mapEmail($email->getFrom()),
34
                $this->mapEmails($email->getTos()),
35
                $email->getSubject(),
36
                $email->getHtmlBody(),
37
                $email->getTextBody(),
38
                null,
39
                true,
40
                $this->mapEmails($email->getReplyTos()),
41
                $this->mapEmails($email->getCcs()),
42
                $this->mapEmails($email->getBccs()),
43
                null,
44
                $this->mapAttachments($email->getAttachments())
45
            );
46
47
            if (!isset($sendResult) || (!isset($sendResult[0]) && !isset($sendResult['ErrorCode']))) {
48
                throw new InvalidRequestException;
49
            } elseif (!isset($sendResult['ErrorCode']) && isset($sendResult[0])) {
50
                $sendResult = $sendResult[0];
51
            }
52
53
            if ((int) $sendResult['ErrorCode'] !== 0) {
54
                $e = new PostmarkException();
55
                $e->httpStatusCode = $sendResult['ErrorCode'];
56
                $e->message = $sendResult['Message'];
57
                $e->postmarkApiErrorCode = $sendResult['ErrorCode'];
58
                throw $e;
59
            }
60
61
            if ($this->logger) {
62
                $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...
63
            }
64
        } catch (Exception $e) {
65
            if ($this->logger) {
66
                $this->logger->info("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...
67
            }
68
            throw $e;
69
        } catch (PostmarkException $e) {
70
            if ($this->logger) {
71
                $this->logger->info("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...
72
            }
73
            switch ($e->postmarkApiErrorCode) {
74
                case 10:
75
                case 400:
76
                case 401:
77
                case 405:
78
                case 500:
79
                case 501:
80
                case 502:
81
                case 503:
82
                    throw new UnauthorizedException($e->message, 602, $e);
83
                case 100:
84
                case 411:
85
                    throw new EmailDeliveryException($e->message, 600, $e);
86
                default:
87
                    throw new InvalidRequestException($e->message, 601, $e);
88
            }
89
        } catch (\Exception $e) {
90
            if ($this->logger) {
91
                $this->logger->info("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...
92
            }
93
            throw new Exception($e->getMessage(), $e->getCode(), $e);
94
        }
95
    }
96
97
    /**
98
     * @param array|null $attachments
99
     * @return array|null
100
     */
101
    private function mapAttachments(array $attachments = null)
102
    {
103
        if (null === $attachments || !is_array($attachments) || !count($attachments)) {
104
            return null;
105
        }
106
107
        $finalAttachments = [];
108
        /** @var AttachmentInterface $attachment */
109
        foreach ($attachments as $attachment) {
110
            $finalAttachment = [
111
                'ContentType' => $attachment->getMimeType(),
112
                'Name' => $attachment->getName()
113
            ];
114
            if (!$attachment->getPath() && $attachment->getContent()) {
115
                $finalAttachment['Content'] = base64_encode($attachment->getContent());
116
            } elseif ($attachment->getPath()) {
117
                $finalAttachment['Content'] = base64_encode(file_get_contents($attachment->getPath()));
118
            }
119
120
            if ($attachment->getContentId()) {
121
                $finalAttachment['ContentId'] = $attachment->getContentId();
122
            }
123
124
            $finalAttachments[] = $finalAttachment;
125
        }
126
        return $finalAttachments;
127
    }
128
129
    /**
130
     * @param array $emails
131
     * @return string
132
     */
133 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...
134
    {
135
        $returnValue = '';
136
        foreach ($emails as $email) {
137
            $returnValue .= $this->mapEmail($email) . ', ';
138
        }
139
        return $returnValue ? substr($returnValue, 0, -2) : '';
140
    }
141
142
    /**
143
     * @param array $email
144
     * @return string
145
     */
146
    private function mapEmail(array $email)
147
    {
148
        return !empty($email['name']) ? "'{$email['name']}' <{$email['email']}>" : $email['email'];
149
    }
150
}
151