1 | <?php |
||||
2 | |||||
3 | /* |
||||
4 | * This file is part of the Koded package. |
||||
5 | * |
||||
6 | * (c) Mihail Binev <[email protected]> |
||||
7 | * |
||||
8 | * Please view the LICENSE distributed with this source code |
||||
9 | * for the full copyright and license information. |
||||
10 | * |
||||
11 | */ |
||||
12 | |||||
13 | namespace Koded\Http\Client; |
||||
14 | |||||
15 | use Koded\Http\{ClientRequest, ServerResponse}; |
||||
16 | use Koded\Http\Interfaces\{HttpRequestClient, HttpStatus, Response}; |
||||
17 | use Psr\Http\Message\UriInterface; |
||||
18 | use function Koded\Http\create_stream; |
||||
19 | use function Koded\Stdlib\json_serialize; |
||||
20 | |||||
21 | /** |
||||
22 | * @link http://php.net/manual/en/context.curl.php |
||||
23 | */ |
||||
24 | class CurlClient extends ClientRequest implements HttpRequestClient |
||||
25 | { |
||||
26 | use EncodingTrait, Psr18ClientTrait; |
||||
27 | |||||
28 | private array $options = [ |
||||
29 | CURLOPT_MAXREDIRS => 20, |
||||
30 | CURLOPT_RETURNTRANSFER => true, |
||||
31 | CURLOPT_FOLLOWLOCATION => true, |
||||
32 | CURLOPT_SSL_VERIFYPEER => 1, |
||||
33 | CURLOPT_SSL_VERIFYHOST => 2, |
||||
34 | CURLOPT_USERAGENT => self::USER_AGENT, |
||||
35 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, |
||||
36 | CURLOPT_FAILONERROR => 0, |
||||
37 | ]; |
||||
38 | |||||
39 | private array $responseHeaders = []; |
||||
40 | |||||
41 | public function __construct( |
||||
42 | string $method, |
||||
43 | 19 | string|UriInterface $uri, |
|||
44 | string|iterable $body = null, |
||||
45 | 19 | array $headers = []) |
|||
46 | 19 | { |
|||
47 | 19 | parent::__construct($method, $uri, $body, $headers); |
|||
48 | $this->options[CURLOPT_TIMEOUT] = (\ini_get('default_socket_timeout') ?: 10.0) * 1.0; |
||||
49 | 15 | } |
|||
50 | |||||
51 | 15 | public function read(): Response |
|||
52 | 1 | { |
|||
53 | if ($resource = $this->assertSafeMethod()) { |
||||
54 | return $resource; |
||||
55 | 14 | } |
|||
56 | 14 | $this->prepareRequestBody(); |
|||
57 | $this->prepareOptions(); |
||||
58 | try { |
||||
59 | 14 | if (false === $resource = $this->createResource()) { |
|||
0 ignored issues
–
show
introduced
by
![]() |
|||||
60 | 1 | return $this->getPhpError(HttpStatus::FAILED_DEPENDENCY, |
|||
61 | 1 | 'The HTTP client is not created therefore cannot read anything'); |
|||
62 | 1 | } |
|||
63 | \curl_setopt_array($resource, $this->options); |
||||
64 | $response = \curl_exec($resource); |
||||
65 | 12 | if ($this->hasError($resource)) { |
|||
66 | 11 | return $this->getCurlError(HttpStatus::FAILED_DEPENDENCY, $resource); |
|||
67 | } |
||||
68 | 11 | return new ServerResponse( |
|||
69 | 4 | $response, |
|||
70 | 4 | \curl_getinfo($resource, CURLINFO_RESPONSE_CODE), |
|||
71 | $this->responseHeaders); |
||||
72 | } catch (\TypeError $e) { |
||||
73 | 7 | return $this->getPhpError(HttpStatus::FAILED_DEPENDENCY, $e->getMessage()); |
|||
74 | 7 | } catch (\Throwable $e) { |
|||
75 | 7 | return $this->getPhpError(HttpStatus::INTERNAL_SERVER_ERROR, $e->getMessage()); |
|||
76 | 7 | } finally { |
|||
77 | unset($response); |
||||
78 | 2 | } |
|||
79 | 2 | } |
|||
80 | |||||
81 | 14 | public function userAgent(string $value): HttpRequestClient |
|||
82 | { |
||||
83 | 14 | $this->options[CURLOPT_USERAGENT] = $value; |
|||
84 | 14 | return $this; |
|||
85 | } |
||||
86 | |||||
87 | public function followLocation(bool $value): HttpRequestClient |
||||
88 | { |
||||
89 | 1 | $this->options[CURLOPT_FOLLOWLOCATION] = $value; |
|||
90 | return $this; |
||||
91 | 1 | } |
|||
92 | |||||
93 | 1 | public function maxRedirects(int $value): HttpRequestClient |
|||
94 | { |
||||
95 | $this->options[CURLOPT_MAXREDIRS] = $value; |
||||
96 | 1 | return $this; |
|||
97 | } |
||||
98 | 1 | ||||
99 | public function timeout(float $value): HttpRequestClient |
||||
100 | 1 | { |
|||
101 | $this->options[CURLOPT_TIMEOUT] = $value; |
||||
102 | return $this; |
||||
103 | 2 | } |
|||
104 | |||||
105 | 2 | public function ignoreErrors(bool $value): HttpRequestClient |
|||
106 | { |
||||
107 | 2 | // false = do not fail on error |
|||
108 | $this->options[CURLOPT_FAILONERROR] = (int)!$value; |
||||
109 | return $this; |
||||
110 | 11 | } |
|||
111 | |||||
112 | 11 | public function verifySslHost(bool $value): HttpRequestClient |
|||
113 | { |
||||
114 | 11 | $this->options[CURLOPT_SSL_VERIFYHOST] = $value ? 2 : 0; |
|||
115 | return $this; |
||||
116 | } |
||||
117 | 1 | ||||
118 | public function verifySslPeer(bool $value): HttpRequestClient |
||||
119 | { |
||||
120 | 1 | $this->options[CURLOPT_SSL_VERIFYPEER] = $value ? 1 : 0; |
|||
121 | return $this; |
||||
122 | 1 | } |
|||
123 | |||||
124 | public function withProtocolVersion($version): static |
||||
125 | 1 | { |
|||
126 | $instance = parent::withProtocolVersion($version); |
||||
127 | 1 | $instance->options[CURLOPT_HTTP_VERSION] = |
|||
128 | ['1.1' => CURL_HTTP_VERSION_1_1, |
||||
129 | 1 | '1.0' => CURL_HTTP_VERSION_1_0][$version]; |
|||
130 | return $instance; |
||||
0 ignored issues
–
show
|
|||||
131 | } |
||||
132 | 1 | ||||
133 | protected function createResource(): \CurlHandle|bool |
||||
134 | 1 | { |
|||
135 | return \curl_init((string)$this->getUri()); |
||||
0 ignored issues
–
show
|
|||||
136 | 1 | } |
|||
137 | |||||
138 | protected function hasError($resource): bool |
||||
139 | 1 | { |
|||
140 | return \curl_errno($resource) > 0; |
||||
141 | 1 | } |
|||
142 | |||||
143 | 1 | protected function prepareOptions(): void |
|||
144 | 1 | { |
|||
145 | 1 | $this->options[CURLOPT_HEADERFUNCTION] = [$this, 'extractFromResponseHeaders']; |
|||
146 | 1 | $this->options[CURLOPT_CUSTOMREQUEST] = $this->getMethod(); |
|||
147 | $this->options[CURLOPT_HTTPHEADER] = $this->getFlattenedHeaders(); |
||||
148 | 1 | unset($this->options[CURLOPT_HTTPHEADER][0]); // Host header is always present and first |
|||
149 | } |
||||
150 | |||||
151 | protected function prepareRequestBody(): void |
||||
152 | { |
||||
153 | if (!$this->stream->getSize()) { |
||||
0 ignored issues
–
show
The expression
$this->stream->getSize() of type integer|null is loosely compared to false ; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.
In PHP, under loose comparison (like For 0 == false // true
0 == null // true
123 == false // false
123 == null // false
// It is often better to use strict comparison
0 === false // false
0 === null // false
![]() |
|||||
154 | 11 | return; |
|||
155 | } |
||||
156 | 11 | $this->stream->rewind(); |
|||
157 | if (0 === $this->encoding) { |
||||
158 | $this->options[CURLOPT_POSTFIELDS] = $this->stream->getContents(); |
||||
159 | 10 | } elseif ($content = \json_decode($this->stream->getContents() ?: '[]', true)) { |
|||
160 | $this->normalizeHeader('Content-Type', self::X_WWW_FORM_URLENCODED, true); |
||||
161 | 10 | $this->options[CURLOPT_POSTFIELDS] = \http_build_query($content, null, '&', $this->encoding); |
|||
0 ignored issues
–
show
null of type null is incompatible with the type string expected by parameter $numeric_prefix of http_build_query() .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
162 | } |
||||
163 | $this->stream = create_stream($this->options[CURLOPT_POSTFIELDS]); |
||||
164 | 14 | } |
|||
165 | |||||
166 | 14 | protected function getCurlError(int $status, $resource): Response |
|||
167 | 14 | { |
|||
168 | 14 | //see https://tools.ietf.org/html/rfc7807 |
|||
169 | 14 | return new ServerResponse(json_serialize([ |
|||
170 | 14 | 'title' => \curl_error($resource), |
|||
171 | 'detail' => \curl_strerror(\curl_errno($resource)), |
||||
172 | 14 | 'instance' => \curl_getinfo($resource, CURLINFO_EFFECTIVE_URL), |
|||
173 | 'type' => 'https://httpstatuses.com/' . $status, |
||||
174 | 14 | 'status' => $status, |
|||
175 | 11 | ]), $status, ['Content-Type' => 'application/problem+json']); |
|||
176 | } |
||||
177 | |||||
178 | 3 | /** |
|||
179 | * Extracts the headers from curl response. |
||||
180 | 3 | * |
|||
181 | 1 | * @param resource $_ curl instance |
|||
182 | 2 | * @param string $header Current header line |
|||
183 | 2 | * |
|||
184 | 2 | * @return int Header length |
|||
185 | */ |
||||
186 | protected function extractFromResponseHeaders($_, string $header): int |
||||
187 | 3 | { |
|||
188 | 3 | try { |
|||
189 | [$k, $v] = \explode(':', $header, 2) + [1 => null]; |
||||
190 | 4 | null === $v || $this->responseHeaders[$k] = $v; |
|||
191 | } catch (\Throwable) { |
||||
192 | 4 | /** NOOP **/ |
|||
193 | 4 | } finally { |
|||
194 | 4 | return \mb_strlen($header); |
|||
195 | 4 | } |
|||
196 | 4 | } |
|||
197 | } |
||||
198 |