Completed
Push — master ( 48e5b8...eb0757 )
by Tobias
20:40
created

Message::getBatchMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
/*
4
 * Copyright (C) 2013 Mailgun
5
 *
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Mailgun\Api;
11
12
use Mailgun\Assert;
13
use Mailgun\Exception\InvalidArgumentException;
14
use Mailgun\Message\BatchMessage;
15
use Mailgun\Model\Message\SendResponse;
16
use Mailgun\Model\Message\ShowResponse;
17
18
/**
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class Message extends HttpApi
22
{
23
    /**
24
     * @param string $domain
25
     * @param bool   $autoSend
26
     *
27
     * @return BatchMessage
28
     */
29
    public function getBatchMessage($domain, $autoSend = true)
30
    {
31
        return new BatchMessage($this, $domain, $autoSend);
32
    }
33
34
    /**
35
     * @param string $domain
36
     * @param array  $params
37
     *
38
     * @return SendResponse
39
     */
40
    public function send($domain, array $params)
41
    {
42
        Assert::string($domain);
43
        Assert::notEmpty($domain);
44
        Assert::notEmpty($params);
45
46
        $postDataMultipart = [];
47
        $fields = ['attachment', 'inline'];
48
        foreach ($fields as $fieldName) {
49
            if (!isset($params[$fieldName])) {
50
                continue;
51
            }
52
53
            Assert::isArray($params[$fieldName]);
54
            foreach ($params[$fieldName] as $file) {
55
                $postDataMultipart[] = $this->prepareFile($fieldName, $file);
56
            }
57
58
            unset($params[$fieldName]);
59
        }
60
61 1
        $postDataMultipart = array_merge($this->prepareMultipartParameters($params), $postDataMultipart);
62
        $response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart);
63 1
64 1
        return $this->hydrateResponse($response, SendResponse::class);
65 1
    }
66 1
67 1
    /**
68
     * @param string $domain
69 1
     * @param array  $recipients with all you send emails to. Including bcc and cc
70 1
     * @param string $message    Message filepath or content
71
     * @param array  $params
72 1
     */
73
    public function sendMime($domain, array $recipients, $message, array $params)
74 1
    {
75
        Assert::string($domain);
76 1
        Assert::notEmpty($domain);
77 1
        Assert::notEmpty($recipients);
78 1
        Assert::notEmpty($message);
79
        Assert::nullOrIsArray($params);
80 1
81 1
        $params['to'] = $recipients;
82
        $postDataMultipart = $this->prepareMultipartParameters($params);
83 1
84
        if (is_file($message)) {
85
            $fileData = ['filePath' => $message];
86
        } else {
87
            $fileData = [
88
                'fileContent' => $message,
89
                'filename' => 'message',
90
            ];
91
        }
92
        $postDataMultipart[] = $this->prepareFile('message', $fileData);
93
        $response = $this->httpPostRaw(sprintf('/v3/%s/messages.mime', $domain), $postDataMultipart);
94
95
        return $this->hydrateResponse($response, SendResponse::class);
96
    }
97
98
    /**
99
     * Get stored message.
100
     *
101
     * @param string $url
102
     * @param bool   $rawMessage if true we will use "Accept: message/rfc2822" header
103
     *
104
     * @return ShowResponse
105
     */
106
    public function show($url, $rawMessage = false)
107
    {
108
        Assert::notEmpty($url);
109
110
        $headers = [];
111
        if ($rawMessage) {
112
            $headers['Accept'] = 'message/rfc2822';
113
        }
114
115
        $response = $this->httpGet($url, [], $headers);
116
117
        return $this->hydrateResponse($response, ShowResponse::class);
118 1
    }
119
120 1
    /**
121
     * Prepare a file.
122 1
     *
123
     * @param string $fieldName
124 1
     * @param array  $filePath  array('fileContent' => 'content') or array('filePath' => '/foo/bar')
125 1
     *
126 1
     * @return array
127 1
     *
128
     * @throws InvalidArgumentException
129
     */
130
    private function prepareFile($fieldName, array $filePath)
131
    {
132
        $filename = isset($filePath['filename']) ? $filePath['filename'] : null;
133
134
        if (isset($filePath['fileContent'])) {
135
            // File from memory
136
            $resource = fopen('php://temp', 'r+');
137
            fwrite($resource, $filePath['fileContent']);
138
            rewind($resource);
139
        } elseif (isset($filePath['filePath'])) {
140
            // File form path
141
            $path = $filePath['filePath'];
142 1
143 1
            // Remove leading @ symbol
144 1
            if (0 === strpos($path, '@')) {
145 1
                $path = substr($path, 1);
146
            }
147
148
            $resource = fopen($path, 'r');
149
        } else {
150
            throw new InvalidArgumentException('When using a file you need to specify parameter "fileContent" or "filePath"');
151
        }
152
153
        return [
154
            'name' => $fieldName,
155 1
            'content' => $resource,
156
            'filename' => $filename,
157 1
        ];
158 1
    }
159
160 1
    /**
161 1
     * Prepare multipart parameters. Make sure each POST parameter is split into an array with 'name' and 'content' keys.
162 1
     *
163 1
     * @param array $params
164
     *
165 1
     * @return array
166 1
     */
167
    private function prepareMultipartParameters(array $params)
168 1
    {
169
        $postDataMultipart = [];
170
        foreach ($params as $key => $value) {
171
            // If $value is not an array we cast it to an array
172
            foreach ((array) $value as $subValue) {
173
                $postDataMultipart[] = [
174
                    'name' => $key,
175
                    'content' => $subValue,
176
                ];
177
            }
178
        }
179
180
        return $postDataMultipart;
181
    }
182
}
183