1 | <?php declare(strict_types = 1); |
||
22 | class CurlDriver implements ApiClientDriver |
||
23 | { |
||
24 | |||
25 | /** @var int */ |
||
26 | private $timeout = 20; |
||
27 | |||
28 | /** |
||
29 | * @param HttpMethod $method |
||
30 | * @param string $url |
||
31 | * @param mixed[]|null $data |
||
32 | * @param string[] $headers |
||
33 | * @return Response |
||
34 | * @throws CurlDriverException |
||
35 | */ |
||
36 | public function request(HttpMethod $method, string $url, ?array $data, array $headers = []): Response |
||
37 | { |
||
38 | $ch = curl_init($url); |
||
39 | |||
40 | 2 | if ($ch === false) { |
|
41 | throw new ErrorException('Failed to initialize curl resource.'); |
||
42 | 2 | } |
|
43 | |||
44 | 2 | if ($method->equalsValue(HttpMethod::POST) || $method->equalsValue(HttpMethod::PUT)) { |
|
45 | 2 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method->getValue()); |
|
46 | 2 | curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); |
|
47 | } |
||
48 | |||
49 | 2 | curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); |
|
50 | 2 | curl_setopt($ch, CURLOPT_COOKIESESSION, true); |
|
51 | 2 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
52 | 2 | curl_setopt($ch, CURLOPT_HEADER, true); |
|
53 | 2 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); |
|
54 | 2 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [ |
|
55 | 2 | 'Content-Type: application/json', |
|
56 | ]); |
||
57 | 2 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); |
|
58 | 2 | $output = curl_exec($ch); |
|
59 | |||
60 | 2 | if ($output === false) { |
|
61 | 1 | throw new CurlDriverException($ch); |
|
62 | } |
||
63 | |||
64 | 1 | $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); |
|
65 | 1 | $headers = substr((string) $output, 0, $headerSize); |
|
66 | 1 | $body = substr((string) $output, $headerSize); |
|
67 | |||
68 | 1 | $responseCode = ResponseCode::get(curl_getinfo($ch, CURLINFO_HTTP_CODE)); |
|
69 | |||
70 | 1 | curl_close($ch); |
|
71 | |||
72 | 1 | return new Response( |
|
73 | 1 | $responseCode, |
|
74 | 1 | json_decode($body, true), |
|
75 | 1 | $this->parseHeaders($headers) |
|
76 | ); |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * @param string $rawHeaders |
||
81 | * @return string[] |
||
82 | */ |
||
83 | 1 | private function parseHeaders(string $rawHeaders): array |
|
99 | |||
100 | } |
||
101 |