Completed
Push — master ( 7ba991...d4ab1b )
by Tobias
03:56
created

Message::prepareMultipartParameters()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

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