Completed
Pull Request — master (#61)
by Michal
04:05
created

ConsoleRequest::makeRequest()   D

Complexity

Conditions 15
Paths 64

Size

Total Lines 90

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 49
CRAP Score 17.4683

Importance

Changes 0
Metric Value
dl 0
loc 90
ccs 49
cts 63
cp 0.7778
rs 4.9515
c 0
b 0
f 0
cc 15
nc 64
nop 5
crap 17.4683

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Tomaj\NetteApi\Misc;
4
5
use Nette\Http\FileUpload;
6
use Tomaj\NetteApi\Handlers\ApiHandlerInterface;
7
use Tomaj\NetteApi\Params\InputParam;
8
use Tomaj\NetteApi\Params\ParamInterface;
9
10
class ConsoleRequest
11
{
12
    /** @var ApiHandlerInterface */
13
    private $handler;
14
15 3
    public function __construct(ApiHandlerInterface $handler)
16
    {
17 3
        $this->handler = $handler;
18 3
    }
19
20 3
    public function makeRequest(string $url, string $method, array $values, array $additionalValues = [], ?string $token = null): ConsoleResponse
21
    {
22 3
        list($postFields, $getFields, $cookieFields, $rawPost, $putFields) = $this->processValues($values);
23
24 3
        $postFields = array_merge($postFields, $additionalValues['postFields'] ?? []);
25 3
        $getFields = array_merge($getFields, $additionalValues['getFields'] ?? []);
26 3
        $cookieFields = array_merge($cookieFields, $additionalValues['cookieFields'] ?? []);
27 3
        $putFields = array_merge($putFields, $additionalValues['putFields'] ?? []);
28
29 3
        $postFields = $this->normalizeValues($postFields);
30 3
        $getFields = $this->normalizeValues($getFields);
31 3
        $putFields = $this->normalizeValues($putFields);
32
33 3
        if (count($getFields)) {
34 3
            $parts = [];
35 3
            foreach ($getFields as $key => $value) {
36 3
                $parts[] = "$key=$value";
37
            }
38 3
            $url = $url . '?' . implode('&', $parts);
39
        }
40
41 3
        $putRawPost = null;
42 3
        if (count($putFields)) {
43
            $parts = [];
44
            foreach ($putFields as $key => $value) {
45
                $parts[] = "$key=$value";
46
            }
47
            $putRawPost = implode('&', $parts);
48
        }
49
50 3
        $startTime = microtime(true);
51
52 3
        $curl = curl_init();
53 3
        curl_setopt($curl, CURLOPT_URL, $url);
54 3
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
55 3
        curl_setopt($curl, CURLOPT_NOBODY, false);
56 3
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
57 3
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
58 3
        curl_setopt($curl, CURLOPT_VERBOSE, false);
59 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
60 3
        curl_setopt($curl, CURLOPT_HEADER, true);
61
62 3
        if (count($postFields) || $rawPost || $putRawPost !== null) {
63
            curl_setopt($curl, CURLOPT_POST, true);
64
            curl_setopt($curl, CURLOPT_POSTFIELDS, count($postFields) ? $postFields : ($rawPost ?: $putRawPost));
65
        }
66
67 3
        if (count($cookieFields)) {
68
            $parts = [];
69
            foreach ($cookieFields as $key => $value) {
70
                $parts[] = "$key=$value";
71
            }
72
            curl_setopt($curl, CURLOPT_HTTPHEADER, ["Cookie: " . implode('&', $parts)]);
73
        }
74
75 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
76 3
        $headers = [];
77 3
        if ($token !== null && $token !== false) {
78
            $headers = ['Authorization: Bearer ' . $token];
79
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
80
        }
81
82 3
        $consoleResponse = new ConsoleResponse(
83 3
            $url,
84 2
            $method,
85 2
            $postFields,
86 2
            $getFields,
87 2
            $cookieFields,
88 2
            $headers,
89 2
            $rawPost
90
        );
91
92 3
        $response = curl_exec($curl);
93 3
        $elapsed = intval((microtime(true) - $startTime) * 1000);
94
95 3
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
96 3
        $responseHeaders = substr($response, 0, $headerSize);
97 3
        $responseBody = substr($response, $headerSize);
98
99 3
        $curlErrorNumber = curl_errno($curl);
100 3
        $curlError = curl_error($curl);
101 3
        if ($curlErrorNumber > 0) {
102 3
            $consoleResponse->logError($curlErrorNumber, $curlError, $elapsed);
103
        } else {
104
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
105
            $consoleResponse->logRequest($httpCode, $responseBody, $responseHeaders, $elapsed);
106
        }
107
108 3
        return $consoleResponse;
109
    }
110
111
    /**
112
     * Process given values to POST and GET fields
113
     *
114
     * @param array $values
115
     *
116
     * @return array
117
     */
118 3
    private function processValues(array $values): array
119
    {
120 3
        $params = $this->handler->params();
121
122 3
        $postFields = [];
123 3
        $rawPost = isset($values['post_raw']) ? $values['post_raw'] : false;
124 3
        $getFields = [];
125 3
        $putFields = [];
126 3
        $cookieFields = [];
127
128 3
        foreach ($values as $key => $value) {
129 3
            if (strstr($key, '___') !== false) {
130
                $parts = explode('___', $key);
131
                $key = $parts[0];
132
            }
133
134 3
            foreach ($params as $param) {
135 3
                $valueData = $this->processParam($param, $key, $value);
136 3
                if ($valueData === null) {
137 3
                    continue;
138
                }
139
140 3
                if ($param->isMulti()) {
141
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
142
                        $postFields[$key][] = $valueData;
143
                    } elseif ($param->getType() === InputParam::TYPE_PUT) {
144
                        $putFields[$key][] = $valueData;
145
                    } elseif ($param->getType() === InputParam::TYPE_COOKIE) {
146
                        $cookieFields[$key][] = $valueData;
147
                    } else {
148
                        $getFields[$key][] = $valueData;
149
                    }
150
                } else {
151 3
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
152
                        $postFields[$key] = $valueData;
153 3
                    } elseif ($param->getType() === InputParam::TYPE_PUT) {
154
                        $putFields[$key] = $valueData;
155 3
                    } elseif ($param->getType() === InputParam::TYPE_COOKIE) {
156
                        $cookieFields[$key] = $valueData;
157
                    } else {
158 3
                        $getFields[$key] = $valueData;
159
                    }
160
                }
161
            }
162
        }
163
164 3
        return [$postFields, $getFields, $cookieFields, $rawPost, $putFields];
165
    }
166
167
    /**
168
     * Process one param and returns value
169
     *
170
     * @param ParamInterface  $param   input param
171
     * @param string          $key     param key
172
     * @param mixed           $value   actual value from request
173
     *
174
     * @return string|null
175
     */
176 3
    private function processParam(ParamInterface $param, string $key, $value): ?string
177
    {
178 3
        if ($param->getKey() === $key) {
179 3
            $valueData = $value;
180
181 3
            if ($param->getType() === InputParam::TYPE_FILE) {
182
                /** @var FileUpload $file */
183
                $file = $value;
184
                if ($file->isOk()) {
185
                    $valueData = curl_file_create($file->getTemporaryFile(), $file->getContentType(), $file->getName());
186
                } else {
187
                    $valueData = false;
188
                }
189 3
            } elseif ($param->getType() === InputParam::TYPE_POST_RAW) {
190
                $valueData = file_get_contents('php://input');
191
            }
192
193 3
            return $valueData;
194
        }
195 3
        return null;
196
    }
197
198 3
    private function normalizeValues(array $values): array
199
    {
200 3
        $result = [];
201 3
        foreach ($values as $key => $value) {
202 3
            if (is_array($value)) {
203
                $counter = 0;
204
                foreach ($value as $innerValue) {
205
                    if ($innerValue !== null) {
206
                        $result[$key . "[".$counter++."]"] = $innerValue;
207
                    }
208
                }
209
            } else {
210 3
                $result[$key] = $value;
211
            }
212
        }
213 3
        return $result;
214
    }
215
}
216