Completed
Pull Request — master (#20)
by Tomas
04:02
created

ConsoleRequest::makeRequest()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 57
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 6.2163

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 57
ccs 36
cts 44
cp 0.8182
rs 8.7433
cc 6
eloc 41
nc 16
nop 4
crap 6.2163

How to fix   Long Method   

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) = $this->processValues($values);
38
39 3
        if (count($getFields)) {
40 3
            $url = $url . '?' . implode('&', $getFields);
41 3
        }
42
43 3
        $startTime = microtime();
44
45 3
        $curl = curl_init();
46 3
        curl_setopt($curl, CURLOPT_URL, $url);
47 3
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
48 3
        curl_setopt($curl, CURLOPT_NOBODY, false);
49 3
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
50 3
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
51 3
        curl_setopt($curl, CURLOPT_VERBOSE, false);
52 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
53 3
        curl_setopt($curl, CURLOPT_HEADER, 1);
54 3
        if (count($postFields)) {
55
            curl_setopt($curl, CURLOPT_POST, 1);
56
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
57
        }
58
59 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
60 3
        $headers = [];
61 3
        if ($token !== null && $token !== false) {
62
            $headers = ['Authorization: Bearer ' . $token];
63
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
64
        }
65
66 3
        $consoleResponse = new ConsoleResponse(
67 3
            $url,
68 3
            $method,
69 3
            $postFields,
70 3
            $getFields,
71
            $headers
72 3
        );
73
74 3
        $response = curl_exec($curl);
75 3
        $elapsed = intval((microtime() - $startTime) * 1000);
76
77 3
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
78 3
        $responseHeaders = substr($response, 0, $headerSize);
79 3
        $responseBody = substr($response, $headerSize);
80
81 3
        $curlErrorNumber = curl_errno($curl);
82 3
        $curlError = curl_error($curl);
83 3
        if ($curlErrorNumber > 0) {
84 3
            $consoleResponse->logError($curlErrorNumber, $curlError, $elapsed);
85 3
        } else {
86
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
87
            $consoleResponse->logRequest($httpCode, $responseBody, $responseHeaders, $elapsed);
88
        }
89
90 3
        return $consoleResponse;
91
    }
92
93
    /**
94
     * Process given values to POST and GET fields
95
     *
96
     * @param array $values
97
     *
98
     * @return array
99
     */
100 3
    private function processValues(array $values)
101
    {
102 3
        $params = $this->handler->params();
103
104 3
        $postFields = [];
105 3
        $getFields = [];
106 3
        $fileFields = [];
107
108 3
        foreach ($values as $key => $value) {
109 3
            if (strstr($key, '___') !== false) {
110
                $parts = explode('___', $key);
111
                $key = $parts[0];
112
            }
113
114 3
            foreach ($params as $param) {
115 3
                $valueData = $this->processParam($param, $key, $value);
116 3
                if ($valueData === null) {
117 3
                    continue;
118
                }
119
120 3
                if ($param->getType() == InputParam::TYPE_FILE) {
121
                    $postFields[$key] = $valueData;
122 3
                } elseif ($param->getType() == InputParam::TYPE_POST) {
123
                    $postFields[$key] = $valueData;
124
                } else {
125 3
                    $getFields[$key] = $valueData;
126
                }
127 3
            }
128 3
        }
129
130 3
        return [$postFields, $getFields, $fileFields];
131
    }
132
133
    /**
134
     * Process one param and returns value
135
     *
136
     * @param InputParam  $param   input param
137
     * @param string      $key     param key
138
     * @param string      $value   actual value from request
139
     *
140
     * @return string
141
     */
142 3
    private function processParam(InputParam $param, $key, $value)
143
    {
144 3
        if ($param->getKey() == $key) {
145 3
            if (!$value) {
146
                return null;
147
            }
148
149 3
            if ($param->isMulti()) {
150
                $valueData = $this->processMultiParam($key, $value);
151 3
            } elseif ($param->getType() == InputParam::TYPE_FILE) {
152
                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...
153
                    $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...
154
                } else {
155
                    $valueData = false;
156
                }
157
            } else {
158 3
                $valueData = "$value";
159
            }
160
161 3
            return $valueData;
162
        }
163 3
        return null;
164
    }
165
166
    /**
167
     * Process multi param
168
     *
169
     * @param string  $key
170
     * @param string  $value
171
     * @return string
172
     */
173
    private function processMultiParam($key, $value)
174
    {
175
        $valueKey = '';
176
        if (strstr($value, '=') !== false) {
177
            $parts = explode('=', $value);
178
            $valueKey = $parts[0];
179
            $value = $parts[1];
180
        }
181
        return $key . "[$valueKey]=$value";
182
    }
183
}
184