-
- Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathCurlHttpClient.php
More file actions
106 lines (95 loc) · 2.98 KB
/
CurlHttpClient.php
File metadata and controls
106 lines (95 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* The most popular PHP library for use with the Twitter OAuth REST API.
*
* @license MIT
*/
declare(strict_types=1);
namespace Abraham\TwitterOAuth;
/**
* cURL-based HTTP client implementation
*
* @author Abraham Williams <abraham@abrah.am>
*/
class CurlHttpClient implements HttpClientInterface
{
/**
* Execute an HTTP request using cURL
*
* @param string $url The URL to request
* @param string $method The HTTP method (GET, POST, PUT, DELETE)
* @param array $headers The HTTP headers
* @param string $body The request body
* @param array $curlOptions Additional cURL options
*
* @return array{body: string, headers: array<string, string>, httpCode: int}
* @throws TwitterOAuthException
*/
public function request(
string $url,
string $method,
array $headers,
string $body,
array $curlOptions,
): array {
$curlOptions[CURLOPT_URL] = $url;
$curlOptions[CURLOPT_HTTPHEADER] = $headers;
switch ($method) {
case 'GET':
break;
case 'POST':
$curlOptions[CURLOPT_POST] = true;
if (!empty($body)) {
$curlOptions[CURLOPT_POSTFIELDS] = $body;
}
break;
case 'DELETE':
$curlOptions[CURLOPT_CUSTOMREQUEST] = 'DELETE';
break;
case 'PUT':
$curlOptions[CURLOPT_CUSTOMREQUEST] = 'PUT';
if (!empty($body)) {
$curlOptions[CURLOPT_POSTFIELDS] = $body;
}
break;
}
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $curlOptions);
$response = curl_exec($curlHandle);
// Throw exceptions on cURL errors.
if (curl_errno($curlHandle) > 0) {
$error = curl_error($curlHandle);
$errorNo = curl_errno($curlHandle);
throw new TwitterOAuthException($error, $errorNo);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
$parts = explode("\r\n\r\n", $response);
$responseBody = array_pop($parts);
$responseHeader = array_pop($parts);
$headers = $this->parseHeaders($responseHeader);
return [
'body' => $responseBody,
'headers' => $headers,
'httpCode' => $httpCode,
];
}
/**
* Get the header info to store.
*
* @param string $header
*
* @return array<string, string>
*/
private function parseHeaders(string $header): array
{
$headers = [];
foreach (explode("\r\n", $header) as $line) {
if (strpos($line, ':') !== false) {
[$key, $value] = explode(': ', $line, 2);
$key = str_replace('-', '_', strtolower($key));
$headers[$key] = trim($value);
}
}
return $headers;
}
}