Remote   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 255
Duplicated Lines 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 119
c 5
b 1
f 0
dl 0
loc 255
rs 10
wmc 25

9 Methods

Rating   Name   Duplication   Size   Complexity  
A http() 0 19 1
A get() 0 7 1
A postForm() 0 11 1
B extractHeaders() 0 28 7
A postJson() 0 13 2
B createCurlHandlerFromRequest() 0 43 7
A execute_curl() 0 20 4
A delete() 0 7 1
A __construct() 0 12 1
1
<?php
2
3
namespace alkemann\h2l;
4
5
use alkemann\h2l\exceptions\CurlFailure;
6
use alkemann\h2l\util\Http;
7
use CurlHandle;
8
use Exception;
9
10
/**
11
 * Class Remote
12
 *
13
 * Makes http requests using cURL. uses Message for both Request and Response description
14
 *
15
 * @TODO SSL verify optional
16
 * @TODO Proxy support?
17
 * @package alkemann\h2l
18
 */
19
class Remote
20
{
21
    /**
22
     * @var array<string, mixed>
23
     */
24
    private array $config = [];
25
    /**
26
     * @var array<int, mixed>
27
     */
28
    private array $curl_options = [];
29
    /**
30
     * @psalm-suppress PropertyNotSetInConstructor
31
     * @var CurlHandle
32
     */
33
    private CurlHandle $curl_handler;
34
    /**
35
     * @var float
36
     */
37
    private float $start = 0.0;
38
39
    /**
40
     * Creatues the Remote instance, only sets configurations
41
     *
42
     * @param array<int, mixed> $curl_options
43
     * @param array<string, mixed> $config
44
     */
45
    public function __construct(array $curl_options = [], array $config = [])
46
    {
47
        $this->config = $config;
48
        $this->curl_options = [
49
                CURLOPT_FOLLOWLOCATION => true,
50
                CURLOPT_MAXREDIRS => 10,
51
                CURLOPT_CONNECTTIMEOUT => 10,
52
                CURLOPT_TIMEOUT => 10,
53
                CURLOPT_USERAGENT => 'alkemann-h2l-Remote-0.29',
54
                CURLOPT_RETURNTRANSFER => true,
55
                CURLOPT_HEADER => true,
56
            ] + $curl_options;
57
    }
58
59
    /**
60
     * Make a HTTP GET request to `$url` and return the `Message` response
61
     *
62
     * @param string $url
63
     * @param array $headers
64
     * @return Message
65
     */
66
    public function get(string $url, array $headers = []): Message
67
    {
68
        $request = (new Message())
69
            ->withUrl($url)
70
            ->withMethod(Http::GET)
71
            ->withHeaders($headers);
72
        return $this->http($request);
73
    }
74
75
    /**
76
     * Make a HTTP POST request to `$url`, posting `$data` as a json body, and return the `Message` response
77
     *
78
     * @param string $url
79
     * @param array $data
80
     * @param array $headers
81
     * @param string $method Http::POST | Http::PUT
82
     * @return Message
83
     */
84
    public function postJson(string $url, array $data, array $headers = [], string $method = Http::POST): Message
85
    {
86
        $headers['Content-Type'] = 'application/json; charset=utf-8';
87
        $headers['Accept'] = 'application/json';
88
        $data_string = json_encode($data);
89
        $json = is_string($data_string) ? $data_string : "";
90
        $headers['Content-Length'] = strlen($json);
91
        $request = (new Message())
92
            ->withUrl($url)
93
            ->withMethod($method)
94
            ->withBody($json)
95
            ->withHeaders($headers);
96
        return $this->http($request);
97
    }
98
99
    /**
100
     * Make a HTTP POST request to `$url`, posting `$data` as a "form" and return the `Message` response
101
     *
102
     * @param string $url
103
     * @param array $data
104
     * @param array $headers
105
     * @param string $method Http::POST | Http::PUT
106
     * @return Message
107
     */
108
    public function postForm(string $url, array $data, array $headers = [], string $method = Http::POST): Message
109
    {
110
        $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
111
        $data_string = http_build_query($data);
112
        $headers['Content-Length'] = strlen($data_string);
113
        $request = (new Message())
114
            ->withUrl($url)
115
            ->withMethod($method)
116
            ->withBody($data_string)
117
            ->withHeaders($headers);
118
        return $this->http($request);
119
    }
120
121
    /**
122
     * Make a HTTP DELETE request to `$url` and return the `Message` response
123
     *
124
     * @param string $url
125
     * @param array $headers
126
     * @return Message
127
     */
128
    public function delete(string $url, array $headers = []): Message
129
    {
130
        $request = (new Message())
131
            ->withUrl($url)
132
            ->withMethod(Http::DELETE)
133
            ->withHeaders($headers);
134
        return $this->http($request);
135
    }
136
137
    /**
138
     * Make a HTTP request as specified by `$message` and return the `Message` response
139
     *
140
     * @param Message $message
141
     * @return Message
142
     */
143
    public function http(Message $message): Message
144
    {
145
        $this->createCurlHandlerFromRequest($message);
146
        $content = $this->execute_curl($message);
147
        $meta = curl_getinfo($this->curl_handler);
148
        $header_size = curl_getinfo($this->curl_handler, CURLINFO_HEADER_SIZE);
149
        $header = substr($content, 0, $header_size);
150
        $headers = $this->extractHeaders($header);
151
        $content = substr($content, $header_size);
152
        curl_close($this->curl_handler);
153
        unset($this->curl_handler);
154
        $meta['latency'] = microtime(true) - $this->start;
155
        return (new Message())
156
            ->withUrl($message->url())
157
            ->withMethod($message->method())
158
            ->withBody($content)
159
            ->withCode($meta['http_code'])
160
            ->withHeaders($headers)
161
            ->withMeta($meta)
162
        ;
163
    }
164
165
    /**
166
     * @param Message $request
167
     * @throws Exception if CurlInit fails
168
     */
169
    private function createCurlHandlerFromRequest(Message $request): void
170
    {
171
        $this->start = microtime(true);
0 ignored issues
show
Documentation Bug introduced by
It seems like microtime(true) can also be of type string. However, the property $start is declared as type double. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
172
173
        $handle = curl_init();
174
175
        if ($handle == false) {
176
            throw new Exception("Curl Init failed!");
177
        }
178
179
        $this->curl_handler = $handle;
0 ignored issues
show
Documentation Bug introduced by
It seems like $handle can also be of type resource. However, the property $curl_handler is declared as type CurlHandle. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
180
181
        $options = $this->curl_options;
182
        $options += [
183
            CURLOPT_URL => $request->url(),
184
            CURLOPT_CUSTOMREQUEST => $request->method(),
185
        ];
186
187
        if (!isset($options[CURLOPT_HTTPHEADER])) {
188
            $options[CURLOPT_HTTPHEADER] = [];
189
        }
190
        $body = $request->body();
191
        if (empty($body) === false) {
192
            $options[CURLOPT_POSTFIELDS] = $body;
193
        }
194
195
        foreach ($request->headers() as $header_name => $header_value) {
196
            $options[CURLOPT_HTTPHEADER][] = "{$header_name}: {$header_value}";
197
        }
198
199
        $headers_to_set_to_blank_if_not_set = [
200
            'Content-Type',
201
            'Expect',
202
            'Accept',
203
            'Accept-Encoding'
204
        ];
205
        foreach ($headers_to_set_to_blank_if_not_set as $name) {
206
            if ($request->header($name) === null) {
207
                $options[CURLOPT_HTTPHEADER][] = "{$name}:";
208
            }
209
        }
210
211
        curl_setopt_array($this->curl_handler, $options);
212
    }
213
214
    /**
215
     * @param Message $request
216
     * @return string
217
     * @throws CurlFailure if curl_exec returns false or throws an Exception
218
     */
219
    private function execute_curl(Message $request): string
220
    {
221
        try {
222
            $content = curl_exec($this->curl_handler);
223
            if ($content === false || is_string($content) === false) {
224
                throw new CurlFailure(curl_error($this->curl_handler), curl_errno($this->curl_handler));
225
            }
226
            return $content;
227
        } catch (Exception $e) {
228
            Log::error("CURL exception : " . get_class($e) . " : " . $e->getMessage());
229
230
            $curl_failure = new CurlFailure($e->getMessage(), (int) $e->getCode(), $e);
231
            $latency = microtime(true) - $this->start;
232
            $info = curl_getinfo($this->curl_handler);
233
            $curl_failure->setContext(compact('request', 'latency', 'info'));
234
235
            curl_close($this->curl_handler);
236
            unset($this->curl_handler);
237
238
            throw $curl_failure;
239
        }
240
    }
241
242
    /**
243
     * @param string $header
244
     * @return array
245
     */
246
    private function extractHeaders(string $header): array
247
    {
248
        $parts = explode("\n", $header);
249
        $result = [];
250
        foreach ($parts as $part) {
251
            $part = trim($part);
252
            if (empty($part)) {
253
                continue;
254
            }
255
256
            if (strpos($part, ': ') !== false) {
257
                list($key, $value) = explode(": ", $part);
258
                $result[$key] = trim($value);
259
                continue;
260
            }
261
262
            $regex = '#^HTTP/(\d\.\d) (\d{3})(.*)#';
263
            if (preg_match($regex, $part, $matches)) {
264
                if (!empty($result)) {
265
                    $result = ['redirected' => $result];
266
                }
267
268
                $result['Http-Version'] = $matches[1];
269
                $result['Http-Code'] = $matches[2];
270
                $result['Http-Message'] = $matches[3] ? trim($matches[3]) : '';
271
            }
272
        }
273
        return $result;
274
    }
275
}
276