Completed
Push — master ( 80a825...d4e4d4 )
by Tobias
04:32
created

Message::closeResources()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

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