Completed
Push — master ( 060c67...cb2641 )
by Tomas
02:33
created

ConsoleRequest::processMultiParam()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
crap 6
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
        $postFields = $this->normalizeValues($postFields);
40 3
        $getFields = $this->normalizeValues($getFields);
41
42 3
        if (count($getFields)) {
43 3
            $parts = [];
44 3
            foreach ($getFields as $key => $value) {
45 3
                $parts[] = "$key=$value";
46 3
            }
47 3
            $url = $url . '?' . implode('&', $parts);
48 3
        }
49
50 3
        $startTime = microtime();
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 3
        if (count($postFields)) {
62
            curl_setopt($curl, CURLOPT_POST, true);
63
64
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
65
        }
66
67 3
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
68 3
        $headers = [];
69 3
        if ($token !== null && $token !== false) {
70
            $headers = ['Authorization: Bearer ' . $token];
71
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
72
        }
73
74 3
        $consoleResponse = new ConsoleResponse(
75 3
            $url,
76 3
            $method,
77 3
            $postFields,
78 3
            $getFields,
79
            $headers
80 3
        );
81
82 3
        $response = curl_exec($curl);
83 3
        $elapsed = intval((microtime() - $startTime) * 1000);
84
85 3
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
86 3
        $responseHeaders = substr($response, 0, $headerSize);
87 3
        $responseBody = substr($response, $headerSize);
88
89 3
        $curlErrorNumber = curl_errno($curl);
90 3
        $curlError = curl_error($curl);
91 3
        if ($curlErrorNumber > 0) {
92 3
            $consoleResponse->logError($curlErrorNumber, $curlError, $elapsed);
93 3
        } else {
94
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
95
            $consoleResponse->logRequest($httpCode, $responseBody, $responseHeaders, $elapsed);
96
        }
97
98 3
        return $consoleResponse;
99
    }
100
101
    /**
102
     * Process given values to POST and GET fields
103
     *
104
     * @param array $values
105
     *
106
     * @return array
107
     */
108 3
    private function processValues(array $values)
109
    {
110 3
        $params = $this->handler->params();
111
112 3
        $postFields = [];
113 3
        $getFields = [];
114
115
116 3
        foreach ($values as $key => $value) {
117 3
            if (strstr($key, '___') !== false) {
118
                $parts = explode('___', $key);
119
                $key = $parts[0];
120
            }
121
122 3
            foreach ($params as $param) {
123 3
                $valueData = $this->processParam($param, $key, $value);
124
125 3
                if ($valueData === null) {
126 3
                    continue;
127
                }
128
129 3
                if ($param->isMulti()) {
130 View Code Duplication
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
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...
131
                        $postFields[$key][] = $valueData;
132
                    } else {
133
                        $getFields[$key][] = $valueData;
134
                    }
135 View Code Duplication
                } else {
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...
136 3
                    if (in_array($param->getType(), [InputParam::TYPE_POST, InputParam::TYPE_FILE])) {
137
                        $postFields[$key] = $valueData;
138
                    } else {
139 3
                        $getFields[$key] = $valueData;
140
                    }
141
                }
142 3
            }
143 3
        }
144
145 3
        return [$postFields, $getFields];
146
    }
147
148
    /**
149
     * Process one param and returns value
150
     *
151
     * @param InputParam  $param   input param
152
     * @param string      $key     param key
153
     * @param string      $value   actual value from request
154
     *
155
     * @return string
156
     */
157 3
    private function processParam(InputParam $param, $key, $value)
158
    {
159 3
        if ($param->getKey() == $key) {
160 3
            if (!$value) {
161
                return null;
162
            }
163
164 3
            $valueData = $value;
165
166 3
            if ($param->getType() == InputParam::TYPE_FILE) {
167
                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...
168
                    $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...
169
                } else {
170
                    $valueData = false;
171
                }
172
            }
173
174 3
            return $valueData;
175
        }
176 3
        return null;
177
    }
178
179
    /**
180
     * Normalize values array.
181
     *
182
     * @param $values
183
     * @return array
184
     */
185 3
    private function normalizeValues($values)
186
    {
187 3
        $result = [];
188 3
        foreach ($values as $key => $value) {
189 3
            if (is_array($value)) {
190
                $counter = 0;
191
                foreach ($value as $innerValue) {
192
                    if ($innerValue != null) {
193
                        $result[$key . "[".$counter++."]"] = $innerValue;
194
                    }
195
                }
196
            } else {
197 3
                $result[$key] = $value;
198
            }
199 3
        }
200 3
        return $result;
201
    }
202
}
203