-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCurlTransport.php
More file actions
68 lines (56 loc) · 2.04 KB
/
CurlTransport.php
File metadata and controls
68 lines (56 loc) · 2.04 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
<?php
namespace OpenApi\Transports;
use OpenApi\Interfaces\HttpTransportInterface;
final class CurlTransport implements HttpTransportInterface
{
public function __construct(
private ?string $token = null
) {}
/**
* Execute HTTP request
*
* @param string $method HTTP method (GET, POST, PUT, DELETE, PATCH)
* @param string $url Target URL
* @param mixed $payload Request body (for POST/PUT/PATCH)
* @param array|null $params Query parameters (for GET) or form data (for other methods)
* @return string Response body
*/
public function request(
string $method,
string $url,
mixed $payload = null,
?array $params = null
): string {
if ($params && $method === 'GET') {
$url .= '?' . http_build_query($params);
}
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->token,
],
]);
if ($payload && in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, is_string($payload) ? $payload : json_encode($payload));
}
if ($params && $method !== 'GET' && !$payload) {
curl_setopt($ch, CURLOPT_POSTFIELDS, is_string($params) ? $params : http_build_query($params));
}
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$ch = null;
if ($response === false) {
throw new \RuntimeException('cURL error: ' . $error);
}
if ($httpCode >= 400) {
throw new \RuntimeException("HTTP error {$httpCode}: {$response}");
}
return $response;
}
}