Completed
Pull Request — master (#247)
by Tobias
05:45
created

Message   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 119
Duplicated Lines 21.01 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 3
dl 25
loc 119
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C send() 25 45 8
A show() 0 13 2
B prepareFile() 0 31 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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