Completed
Push — master ( b1f949...cc8235 )
by Sean
03:18
created

Message::send()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 45
Code Lines 29

Duplication

Lines 25
Ratio 55.56 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 25
loc 45
ccs 0
cts 33
cp 0
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 29
nc 12
nop 2
crap 72
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\Resource\Api\Message\SendResponse;
15
use Mailgun\Resource\Api\Message\ShowResponse;
16
17
/**
18
 * @author Tobias Nyholm <[email protected]>
19
 */
20
class Message extends HttpApi
21
{
22
    /**
23
     * @param $domain
24
     * @param array $params
25
     *
26
     * @return SendResponse
27
     */
28
    public function send($domain, array $params)
29
    {
30
        Assert::notEmpty($domain);
31
        Assert::notEmpty($params);
32
33
        $postDataMultipart = [];
34
        $fields = ['message', 'attachment', 'inline'];
35
        foreach ($fields as $fieldName) {
36
            if (!isset($params[$fieldName])) {
37
                continue;
38
            }
39 View Code Duplication
            if (!is_array($params[$fieldName])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
40
                $postDataMultipart[] = $this->prepareFile($fieldName, $params[$fieldName]);
41
            } else {
42
                $fileIndex = 0;
43
                foreach ($params[$fieldName] as $file) {
44
                    $postDataMultipart[] = $this->prepareFile($fieldName, $file, $fileIndex);
45
                    ++$fileIndex;
46
                }
47
            }
48
49
            unset($params[$fieldName]);
50
        }
51
52 View Code Duplication
        foreach ($params as $key => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
53
            if (is_array($value)) {
54
                $index = 0;
55
                foreach ($value as $subValue) {
56
                    $postDataMultipart[] = [
57
                        'name' => sprintf('%s[%d]', $key, $index++),
58
                        'content' => $subValue,
59
                    ];
60
                }
61
            } else {
62
                $postDataMultipart[] = [
63
                    'name' => $key,
64
                    'content' => $value,
65
                ];
66
            }
67
        }
68
69
        $response = $this->httpPostRaw(sprintf('/v3/%s/messages', $domain), $postDataMultipart);
70
71
        return $this->safeDeserialize($response, SendResponse::class);
72
    }
73
74
    /**
75
     * Get stored message.
76
     *
77
     * @param string $url
78
     * @param bool   $rawMessage if true we will use "Accept: message/rfc2822" header.
79
     *
80
     * @return ShowResponse
81
     */
82
    public function show($url, $rawMessage = false)
83
    {
84
        Assert::notEmpty($url);
85
86
        $headers = [];
87
        if ($rawMessage) {
88
            $headers['Accept'] = 'message/rfc2822';
89
        }
90
91
        $response = $this->httpGet($url, [], $headers);
92
93
        return $this->safeDeserialize($response, ShowResponse::class);
94
    }
95
96
    /**
97
     * Prepare a file.
98
     *
99
     * @param string $fieldName
100
     * @param array  $filePath  array('fileContent' => 'content') or array('filePath' => '/foo/bar')
101
     * @param int    $fileIndex
102
     *
103
     * @return array
104
     *
105
     * @throws InvalidArgumentException
106
     */
107
    private function prepareFile($fieldName, array $filePath, $fileIndex = 0)
108
    {
109
        // Add index for multiple file support
110
        $fieldName .= '['.$fileIndex.']';
111
        $filename = isset($filePath['filename']) ? $filePath['filename'] : null;
112
113
        if (isset($filePath['fileContent'])) {
114
            // File from memory
115
            $resource = fopen('php://temp', 'r+');
116
            fwrite($resource, $filePath['fileContent']);
117
            rewind($resource);
118
        } elseif (isset($filePath['filePath'])) {
119
            // File form path
120
            $path = $filePath['filePath'];
121
122
            // Remove leading @ symbol
123
            if (strpos($path, '@') === 0) {
124
                $path = substr($path, 1);
125
            }
126
127
            $resource = fopen($path, 'r');
128
        } else {
129
            throw new InvalidArgumentException('When using a file you need to specify parameter "fileContent" or "filePath"');
130
        }
131
132
        return [
133
            'name' => $fieldName,
134
            'content' => $resource,
135
            'filename' => $filename,
136
        ];
137
    }
138
}
139