Completed
Push — master ( a36da0...f71e62 )
by Tomas
11s
created

ConsoleRequest::makeRequest()   F

Complexity

Conditions 13
Paths 256

Size

Total Lines 91
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 50
CRAP Score 15.7596

Importance

Changes 0
Metric Value
dl 0
loc 91
ccs 50
cts 67
cp 0.7463
rs 3.7737
c 0
b 0
f 0
cc 13
eloc 66
nc 256
nop 4
crap 15.7596

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 Tomaj\NetteApi\Handlers\ApiHandlerInterface;
6
use Tomaj\NetteApi\Params\InputParam;
7
8
class ConsoleRequest
9
{
10
    /**
11
     * @var ApiHandlerInterface
12
     */
13
    private $handler;
14
15
    /**
16
     * Create ConsoleRequest
17
     *
18
     * @param ApiHandlerInterface $handler
19
     */
20 3
    public function __construct(ApiHandlerInterface $handler)
21
    {
22 3
        $this->handler = $handler;
23 3
    }
24
25
    /**
26
     * Make request to API url
27
     *
28
     * @param string $url
29
     * @param string $method
30
     * @param array $values
31
     * @param string|null $token
32
     *
33
     * @return ConsoleResponse
34
     */
35 3
    public function makeRequest($url, $method, array $values, $token = null)
36
    {
37 3
        list($postFields, $getFields, $cookieFields, $rawPost, $putFields) = $this->processValues($values);
38
39 3
        $postFields = $this->normalizeValues($postFields);
40 3
        $getFields = $this->normalizeValues($getFields);
41
        $putFields = $this->normalizeValues($putFields);
42 3
43 3
        if (count($getFields)) {
44 3
            $parts = [];
45 3
            foreach ($getFields as $key => $value) {
46 2
                $parts[] = "$key=$value";
47 3
            }
48 2
            $url = $url . '?' . implode('&', $parts);
49
        }
50 3
51
        $putRawPost = null;
52 3
        if (count($putFields)) {
53 3
            $parts = [];
54 3
            foreach ($putFields as $key => $value) {
55 3
                $parts[] = "$key=$value";
56 3
            }
57 3
            $putRawPost = implode('&', $parts);
58 3
        }
59 3
60 3
        $startTime = microtime(true);
61 3
62
        $curl = curl_init();
63
        curl_setopt($curl, CURLOPT_URL, $url);
64
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
65 3
        curl_setopt($curl, CURLOPT_NOBODY, false);
66
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
67
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
68
        curl_setopt($curl, CURLOPT_VERBOSE, false);
69 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
70
        curl_setopt($curl, CURLOPT_HEADER, true);
71
        if (count($postFields)) {
72
            curl_setopt($curl, CURLOPT_POST, true);
73
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
74
        }
75
        if ($rawPost) {
76
            curl_setopt($curl, CURLOPT_POST, true);
77 3
            curl_setopt($curl, CURLOPT_POSTFIELDS, $rawPost);
78 3
        }
79 3
        if ($putRawPost) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $putRawPost of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
80
            curl_setopt($curl, CURLOPT_POST, true);
81
            curl_setopt($curl, CURLOPT_POSTFIELDS, $putRawPost);
82
        }
83
        if (count($cookieFields)) {
84 3
            $parts = [];
85 2
            foreach ($cookieFields as $key => $value) {
86 2
                $parts[] = "$key=$value";
87 2
            }
88 2
            curl_setopt($curl, CURLOPT_HTTPHEADER, ["Cookie: " . implode('&', $parts)]);
89 2
        }
90 2
91
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
92 2
        $headers = [];
93
        if ($token !== null && $token !== false) {
94 3
            $headers = ['Authorization: Bearer ' . $token];
95 3
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
96
        }
97 3
98 3
        $consoleResponse = new ConsoleResponse(
99 3
            $url,
100
            $method,
101 3
            $postFields,
102 3
            $getFields,
103 3
            $cookieFields,
104 3
            $headers,
105 2
            $rawPost
106
        );
107
108
        $response = curl_exec($curl);
109
        $elapsed = intval((microtime(true) - $startTime) * 1000);
110 3
111
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
112
        $responseHeaders = substr($response, 0, $headerSize);
113
        $responseBody = substr($response, $headerSize);
114
115
        $curlErrorNumber = curl_errno($curl);
116
        $curlError = curl_error($curl);
117
        if ($curlErrorNumber > 0) {
118
            $consoleResponse->logError($curlErrorNumber, $curlError, $elapsed);
119
        } else {
120 3
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
121
            $consoleResponse->logRequest($httpCode, $responseBody, $responseHeaders, $elapsed);
122 3
        }
123
124 3
        return $consoleResponse;
125 3
    }
126 3
127 3
    /**
128
     * Process given values to POST and GET fields
129 3
     *
130 3
     * @param array $values
131
     *
132
     * @return array
133
     */
134
    private function processValues(array $values)
135 3
    {
136 3
        $params = $this->handler->params();
137 3
138 3
        $postFields = [];
139
        $rawPost = isset($values['post_raw']) ? $values['post_raw'] : false;
140
        $getFields = [];
141 3
        $putFields = [];
142
        $cookieFields = [];
143
144
        foreach ($values as $key => $value) {
145
            if (strstr($key, '___') !== false) {
146
                $parts = explode('___', $key);
147
                $key = $parts[0];
148
            }
149
150 3
            foreach ($params as $param) {
151
                $valueData = $this->processParam($param, $key, $value);
152 3
                if ($valueData === null) {
153
                    continue;
154
                }
155 3
156
                if ($param->isMulti()) {
157
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
158 2
                        $postFields[$key][] = $valueData;
159 2
                    } elseif ($param->getType() == InputParam::TYPE_PUT) {
160
                        $putFields[$key][] = $valueData;
161 3
                    } elseif ($param->getType() == InputParam::TYPE_COOKIE) {
162
                        $cookieFields[$key][] = $valueData;
163
                    } else {
164
                        $getFields[$key][] = $valueData;
165
                    }
166
                } else {
167
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
168
                        $postFields[$key] = $valueData;
169
                    } elseif ($param->getType() == InputParam::TYPE_PUT) {
170
                        $putFields[$key] = $valueData;
171
                    } elseif ($param->getType() == InputParam::TYPE_COOKIE) {
172
                        $cookieFields[$key] = $valueData;
173 3
                    } else {
174
                        $getFields[$key] = $valueData;
175 3
                    }
176 3
                }
177
            }
178
        }
179
180 3
        return [$postFields, $getFields, $cookieFields, $rawPost, $putFields];
181
    }
182 3
183
    /**
184
     * Process one param and returns value
185
     *
186
     * @param InputParam  $param   input param
187
     * @param string      $key     param key
188
     * @param string      $value   actual value from request
189
     *
190 3
     * @return string
191
     */
192
    private function processParam(InputParam $param, $key, $value)
193
    {
194
        if ($param->getKey() == $key) {
195
            if (!$value) {
196
                return null;
197
            }
198 3
199
            $valueData = $value;
200 3
201
            if ($param->getType() == InputParam::TYPE_FILE) {
202
                if ($value->isOk()) {
0 ignored issues
show
Bug introduced by
The method isOk cannot be called on $value (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
203
                    $valueData = curl_file_create($value->getTemporaryFile(), $value->getContentType(), $value->getName());
0 ignored issues
show
Bug introduced by
The method getTemporaryFile cannot be called on $value (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
The method getContentType cannot be called on $value (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
The method getName cannot be called on $value (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
204
                } else {
205
                    $valueData = false;
206
                }
207
            }
208
209 3
            if ($param->getType() == InputParam::TYPE_POST_RAW) {
210
                if (isset($HTTP_RAW_POST_DATA)) {
0 ignored issues
show
Bug introduced by
The variable $HTTP_RAW_POST_DATA seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
211 3
                    $valueData = $HTTP_RAW_POST_DATA;
212 3
                } else {
213 3
                    $valueData = file_get_contents('php://input');
214
                }
215
            }
216
217
            return $valueData;
218
        }
219
        return null;
220
    }
221 3
222
    /**
223 2
     * Normalize values array.
224 3
     *
225
     * @param $values
226
     * @return array
227
     */
228
    private function normalizeValues($values)
229
    {
230
        $result = [];
231
        foreach ($values as $key => $value) {
232
            if (is_array($value)) {
233
                $counter = 0;
234
                foreach ($value as $innerValue) {
235
                    if ($innerValue != null) {
236
                        $result[$key . "[".$counter++."]"] = $innerValue;
237
                    }
238
                }
239
            } else {
240
                $result[$key] = $value;
241
            }
242
        }
243
        return $result;
244
    }
245
}
246