Completed
Pull Request — master (#20)
by Tomas
06:18 queued 03:24
created

ConsoleRequest::processParam()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 9.6594

Importance

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