Completed
Push — master ( f71e62...3bdf74 )
by Tomas
02:54
created

ConsoleRequest::processValues()   C

Complexity

Conditions 13
Paths 42

Size

Total Lines 48
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 26.6629

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 48
ccs 21
cts 37
cp 0.5676
rs 5.0877
cc 13
eloc 34
nc 42
nop 1
crap 26.6629

How to fix   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 3
        $putFields = $this->normalizeValues($putFields);
42
43 3
        if (count($getFields)) {
44 3
            $parts = [];
45 3
            foreach ($getFields as $key => $value) {
46 3
                $parts[] = "$key=$value";
47 1
            }
48 3
            $url = $url . '?' . implode('&', $parts);
49 1
        }
50
51 3
        $putRawPost = null;
52 3
        if (count($putFields)) {
53
            $parts = [];
54
            foreach ($putFields as $key => $value) {
55
                $parts[] = "$key=$value";
56
            }
57
            $putRawPost = implode('&', $parts);
58
        }
59
60 3
        $startTime = microtime(true);
61
62 3
        $curl = curl_init();
63 3
        curl_setopt($curl, CURLOPT_URL, $url);
64 3
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
65 3
        curl_setopt($curl, CURLOPT_NOBODY, false);
66 3
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
67 3
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
68 3
        curl_setopt($curl, CURLOPT_VERBOSE, false);
69 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
70 3
        curl_setopt($curl, CURLOPT_HEADER, true);
71 3
        if (count($postFields)) {
72
            curl_setopt($curl, CURLOPT_POST, true);
73
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
74
        }
75 3
        if ($rawPost) {
76
            curl_setopt($curl, CURLOPT_POST, true);
77
            curl_setopt($curl, CURLOPT_POSTFIELDS, $rawPost);
78
        }
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 3
        if (count($cookieFields)) {
84
            $parts = [];
85
            foreach ($cookieFields as $key => $value) {
86
                $parts[] = "$key=$value";
87
            }
88
            curl_setopt($curl, CURLOPT_HTTPHEADER, ["Cookie: " . implode('&', $parts)]);
89
        }
90
91 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
92 3
        $headers = [];
93 3
        if ($token !== null && $token !== false) {
94
            $headers = ['Authorization: Bearer ' . $token];
95
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
96
        }
97
98 3
        $consoleResponse = new ConsoleResponse(
99 1
            $url,
100 1
            $method,
101 1
            $postFields,
102 1
            $getFields,
103 1
            $cookieFields,
104 1
            $headers,
105
            $rawPost
106 1
        );
107
108 3
        $response = curl_exec($curl);
109 3
        $elapsed = intval((microtime(true) - $startTime) * 1000);
110
111 3
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
112 3
        $responseHeaders = substr($response, 0, $headerSize);
113 3
        $responseBody = substr($response, $headerSize);
114
115 3
        $curlErrorNumber = curl_errno($curl);
116 3
        $curlError = curl_error($curl);
117 3
        if ($curlErrorNumber > 0) {
118 3
            $consoleResponse->logError($curlErrorNumber, $curlError, $elapsed);
119 1
        } else {
120
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
121
            $consoleResponse->logRequest($httpCode, $responseBody, $responseHeaders, $elapsed);
122
        }
123
124 3
        return $consoleResponse;
125
    }
126
127
    /**
128
     * Process given values to POST and GET fields
129
     *
130
     * @param array $values
131
     *
132
     * @return array
133
     */
134 3
    private function processValues(array $values)
135
    {
136 3
        $params = $this->handler->params();
137
138 3
        $postFields = [];
139 3
        $rawPost = isset($values['post_raw']) ? $values['post_raw'] : false;
140 3
        $getFields = [];
141 3
        $putFields = [];
142 3
        $cookieFields = [];
143
144 3
        foreach ($values as $key => $value) {
145 3
            if (strstr($key, '___') !== false) {
146
                $parts = explode('___', $key);
147
                $key = $parts[0];
148
            }
149
150 3
            foreach ($params as $param) {
151 3
                $valueData = $this->processParam($param, $key, $value);
152 3
                if ($valueData === null) {
153 3
                    continue;
154
                }
155
156 3
                if ($param->isMulti()) {
157
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
158
                        $postFields[$key][] = $valueData;
159
                    } elseif ($param->getType() == InputParam::TYPE_PUT) {
160
                        $putFields[$key][] = $valueData;
161
                    } elseif ($param->getType() == InputParam::TYPE_COOKIE) {
162
                        $cookieFields[$key][] = $valueData;
163
                    } else {
164
                        $getFields[$key][] = $valueData;
165
                    }
166
                } else {
167 3
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
168
                        $postFields[$key] = $valueData;
169 3
                    } elseif ($param->getType() == InputParam::TYPE_PUT) {
170
                        $putFields[$key] = $valueData;
171 3
                    } elseif ($param->getType() == InputParam::TYPE_COOKIE) {
172
                        $cookieFields[$key] = $valueData;
173
                    } else {
174 3
                        $getFields[$key] = $valueData;
175
                    }
176
                }
177 1
            }
178 1
        }
179
180 3
        return [$postFields, $getFields, $cookieFields, $rawPost, $putFields];
181
    }
182
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
     * @return string
191
     */
192 3
    private function processParam(InputParam $param, $key, $value)
193
    {
194 3
        if ($param->getKey() == $key) {
195 3
            $valueData = $value;
196
197 3
            if ($param->getType() == InputParam::TYPE_FILE) {
198
                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...
199
                    $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...
200
                } else {
201
                    $valueData = false;
202
                }
203
            }
204
205 3
            if ($param->getType() == InputParam::TYPE_POST_RAW) {
206
                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...
207
                    $valueData = $HTTP_RAW_POST_DATA;
208
                } else {
209
                    $valueData = file_get_contents('php://input');
210
                }
211
            }
212
213 3
            return $valueData;
214
        }
215 3
        return null;
216
    }
217
218
    /**
219
     * Normalize values array.
220
     *
221
     * @param $values
222
     * @return array
223
     */
224 3
    private function normalizeValues($values)
225
    {
226 3
        $result = [];
227 3
        foreach ($values as $key => $value) {
228 3
            if (is_array($value)) {
229
                $counter = 0;
230
                foreach ($value as $innerValue) {
231
                    if ($innerValue != null) {
232
                        $result[$key . "[".$counter++."]"] = $innerValue;
233
                    }
234
                }
235
            } else {
236 3
                $result[$key] = $value;
237
            }
238 1
        }
239 3
        return $result;
240
    }
241
}
242