@@ -11,8 +11,7 @@ |
||
11 | 11 | * |
12 | 12 | * @final |
13 | 13 | */ |
14 | -class PrepareBodyMiddleware |
|
15 | -{ |
|
14 | +class PrepareBodyMiddleware { |
|
16 | 15 | /** |
17 | 16 | * @var callable(RequestInterface, array): PromiseInterface |
18 | 17 | */ |
@@ -12,75 +12,75 @@ |
||
12 | 12 | */ |
13 | 13 | class PrepareBodyMiddleware |
14 | 14 | { |
15 | - /** |
|
16 | - * @var callable(RequestInterface, array): PromiseInterface |
|
17 | - */ |
|
18 | - private $nextHandler; |
|
19 | - /** |
|
20 | - * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
21 | - */ |
|
22 | - public function __construct(callable $nextHandler) |
|
23 | - { |
|
24 | - $this->nextHandler = $nextHandler; |
|
25 | - } |
|
26 | - public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
27 | - { |
|
28 | - $fn = $this->nextHandler; |
|
29 | - // Don't do anything if the request has no body. |
|
30 | - if ($request->getBody()->getSize() === 0) { |
|
31 | - return $fn($request, $options); |
|
32 | - } |
|
33 | - $modify = []; |
|
34 | - // Add a default content-type if possible. |
|
35 | - if (!$request->hasHeader('Content-Type')) { |
|
36 | - if ($uri = $request->getBody()->getMetadata('uri')) { |
|
37 | - if (\is_string($uri) && ($type = Psr7\MimeType::fromFilename($uri))) { |
|
38 | - $modify['set_headers']['Content-Type'] = $type; |
|
39 | - } |
|
40 | - } |
|
41 | - } |
|
42 | - // Add a default content-length or transfer-encoding header. |
|
43 | - if (!$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding')) { |
|
44 | - $size = $request->getBody()->getSize(); |
|
45 | - if ($size !== null) { |
|
46 | - $modify['set_headers']['Content-Length'] = $size; |
|
47 | - } else { |
|
48 | - $modify['set_headers']['Transfer-Encoding'] = 'chunked'; |
|
49 | - } |
|
50 | - } |
|
51 | - // Add the expect header if needed. |
|
52 | - $this->addExpectHeader($request, $options, $modify); |
|
53 | - return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); |
|
54 | - } |
|
55 | - /** |
|
56 | - * Add expect header |
|
57 | - */ |
|
58 | - private function addExpectHeader(RequestInterface $request, array $options, array &$modify) : void |
|
59 | - { |
|
60 | - // Determine if the Expect header should be used |
|
61 | - if ($request->hasHeader('Expect')) { |
|
62 | - return; |
|
63 | - } |
|
64 | - $expect = $options['expect'] ?? null; |
|
65 | - // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 |
|
66 | - if ($expect === \false || $request->getProtocolVersion() < 1.1) { |
|
67 | - return; |
|
68 | - } |
|
69 | - // The expect header is unconditionally enabled |
|
70 | - if ($expect === \true) { |
|
71 | - $modify['set_headers']['Expect'] = '100-Continue'; |
|
72 | - return; |
|
73 | - } |
|
74 | - // By default, send the expect header when the payload is > 1mb |
|
75 | - if ($expect === null) { |
|
76 | - $expect = 1048576; |
|
77 | - } |
|
78 | - // Always add if the body cannot be rewound, the size cannot be |
|
79 | - // determined, or the size is greater than the cutoff threshold |
|
80 | - $body = $request->getBody(); |
|
81 | - $size = $body->getSize(); |
|
82 | - if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
83 | - $modify['set_headers']['Expect'] = '100-Continue'; |
|
84 | - } |
|
85 | - } |
|
15 | + /** |
|
16 | + * @var callable(RequestInterface, array): PromiseInterface |
|
17 | + */ |
|
18 | + private $nextHandler; |
|
19 | + /** |
|
20 | + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
21 | + */ |
|
22 | + public function __construct(callable $nextHandler) |
|
23 | + { |
|
24 | + $this->nextHandler = $nextHandler; |
|
25 | + } |
|
26 | + public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
27 | + { |
|
28 | + $fn = $this->nextHandler; |
|
29 | + // Don't do anything if the request has no body. |
|
30 | + if ($request->getBody()->getSize() === 0) { |
|
31 | + return $fn($request, $options); |
|
32 | + } |
|
33 | + $modify = []; |
|
34 | + // Add a default content-type if possible. |
|
35 | + if (!$request->hasHeader('Content-Type')) { |
|
36 | + if ($uri = $request->getBody()->getMetadata('uri')) { |
|
37 | + if (\is_string($uri) && ($type = Psr7\MimeType::fromFilename($uri))) { |
|
38 | + $modify['set_headers']['Content-Type'] = $type; |
|
39 | + } |
|
40 | + } |
|
41 | + } |
|
42 | + // Add a default content-length or transfer-encoding header. |
|
43 | + if (!$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding')) { |
|
44 | + $size = $request->getBody()->getSize(); |
|
45 | + if ($size !== null) { |
|
46 | + $modify['set_headers']['Content-Length'] = $size; |
|
47 | + } else { |
|
48 | + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; |
|
49 | + } |
|
50 | + } |
|
51 | + // Add the expect header if needed. |
|
52 | + $this->addExpectHeader($request, $options, $modify); |
|
53 | + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); |
|
54 | + } |
|
55 | + /** |
|
56 | + * Add expect header |
|
57 | + */ |
|
58 | + private function addExpectHeader(RequestInterface $request, array $options, array &$modify) : void |
|
59 | + { |
|
60 | + // Determine if the Expect header should be used |
|
61 | + if ($request->hasHeader('Expect')) { |
|
62 | + return; |
|
63 | + } |
|
64 | + $expect = $options['expect'] ?? null; |
|
65 | + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 |
|
66 | + if ($expect === \false || $request->getProtocolVersion() < 1.1) { |
|
67 | + return; |
|
68 | + } |
|
69 | + // The expect header is unconditionally enabled |
|
70 | + if ($expect === \true) { |
|
71 | + $modify['set_headers']['Expect'] = '100-Continue'; |
|
72 | + return; |
|
73 | + } |
|
74 | + // By default, send the expect header when the payload is > 1mb |
|
75 | + if ($expect === null) { |
|
76 | + $expect = 1048576; |
|
77 | + } |
|
78 | + // Always add if the body cannot be rewound, the size cannot be |
|
79 | + // determined, or the size is greater than the cutoff threshold |
|
80 | + $body = $request->getBody(); |
|
81 | + $size = $body->getSize(); |
|
82 | + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
83 | + $modify['set_headers']['Expect'] = '100-Continue'; |
|
84 | + } |
|
85 | + } |
|
86 | 86 | } |
@@ -79,7 +79,7 @@ |
||
79 | 79 | // determined, or the size is greater than the cutoff threshold |
80 | 80 | $body = $request->getBody(); |
81 | 81 | $size = $body->getSize(); |
82 | - if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
82 | + if ($size === null || $size >= (int)$expect || !$body->isSeekable()) { |
|
83 | 83 | $modify['set_headers']['Expect'] = '100-Continue'; |
84 | 84 | } |
85 | 85 | } |
@@ -10,8 +10,7 @@ |
||
10 | 10 | /** |
11 | 11 | * Client interface for sending HTTP requests. |
12 | 12 | */ |
13 | -trait ClientTrait |
|
14 | -{ |
|
13 | +trait ClientTrait { |
|
15 | 14 | /** |
16 | 15 | * Create and send an HTTP request. |
17 | 16 | * |
@@ -11,217 +11,217 @@ |
||
11 | 11 | */ |
12 | 12 | trait ClientTrait |
13 | 13 | { |
14 | - /** |
|
15 | - * Create and send an HTTP request. |
|
16 | - * |
|
17 | - * Use an absolute path to override the base path of the client, or a |
|
18 | - * relative path to append to the base path of the client. The URL can |
|
19 | - * contain the query string as well. |
|
20 | - * |
|
21 | - * @param string $method HTTP method. |
|
22 | - * @param string|UriInterface $uri URI object or string. |
|
23 | - * @param array $options Request options to apply. |
|
24 | - * |
|
25 | - * @throws GuzzleException |
|
26 | - */ |
|
27 | - public abstract function request(string $method, $uri, array $options = []) : ResponseInterface; |
|
28 | - /** |
|
29 | - * Create and send an HTTP GET request. |
|
30 | - * |
|
31 | - * Use an absolute path to override the base path of the client, or a |
|
32 | - * relative path to append to the base path of the client. The URL can |
|
33 | - * contain the query string as well. |
|
34 | - * |
|
35 | - * @param string|UriInterface $uri URI object or string. |
|
36 | - * @param array $options Request options to apply. |
|
37 | - * |
|
38 | - * @throws GuzzleException |
|
39 | - */ |
|
40 | - public function get($uri, array $options = []) : ResponseInterface |
|
41 | - { |
|
42 | - return $this->request('GET', $uri, $options); |
|
43 | - } |
|
44 | - /** |
|
45 | - * Create and send an HTTP HEAD request. |
|
46 | - * |
|
47 | - * Use an absolute path to override the base path of the client, or a |
|
48 | - * relative path to append to the base path of the client. The URL can |
|
49 | - * contain the query string as well. |
|
50 | - * |
|
51 | - * @param string|UriInterface $uri URI object or string. |
|
52 | - * @param array $options Request options to apply. |
|
53 | - * |
|
54 | - * @throws GuzzleException |
|
55 | - */ |
|
56 | - public function head($uri, array $options = []) : ResponseInterface |
|
57 | - { |
|
58 | - return $this->request('HEAD', $uri, $options); |
|
59 | - } |
|
60 | - /** |
|
61 | - * Create and send an HTTP PUT request. |
|
62 | - * |
|
63 | - * Use an absolute path to override the base path of the client, or a |
|
64 | - * relative path to append to the base path of the client. The URL can |
|
65 | - * contain the query string as well. |
|
66 | - * |
|
67 | - * @param string|UriInterface $uri URI object or string. |
|
68 | - * @param array $options Request options to apply. |
|
69 | - * |
|
70 | - * @throws GuzzleException |
|
71 | - */ |
|
72 | - public function put($uri, array $options = []) : ResponseInterface |
|
73 | - { |
|
74 | - return $this->request('PUT', $uri, $options); |
|
75 | - } |
|
76 | - /** |
|
77 | - * Create and send an HTTP POST request. |
|
78 | - * |
|
79 | - * Use an absolute path to override the base path of the client, or a |
|
80 | - * relative path to append to the base path of the client. The URL can |
|
81 | - * contain the query string as well. |
|
82 | - * |
|
83 | - * @param string|UriInterface $uri URI object or string. |
|
84 | - * @param array $options Request options to apply. |
|
85 | - * |
|
86 | - * @throws GuzzleException |
|
87 | - */ |
|
88 | - public function post($uri, array $options = []) : ResponseInterface |
|
89 | - { |
|
90 | - return $this->request('POST', $uri, $options); |
|
91 | - } |
|
92 | - /** |
|
93 | - * Create and send an HTTP PATCH request. |
|
94 | - * |
|
95 | - * Use an absolute path to override the base path of the client, or a |
|
96 | - * relative path to append to the base path of the client. The URL can |
|
97 | - * contain the query string as well. |
|
98 | - * |
|
99 | - * @param string|UriInterface $uri URI object or string. |
|
100 | - * @param array $options Request options to apply. |
|
101 | - * |
|
102 | - * @throws GuzzleException |
|
103 | - */ |
|
104 | - public function patch($uri, array $options = []) : ResponseInterface |
|
105 | - { |
|
106 | - return $this->request('PATCH', $uri, $options); |
|
107 | - } |
|
108 | - /** |
|
109 | - * Create and send an HTTP DELETE request. |
|
110 | - * |
|
111 | - * Use an absolute path to override the base path of the client, or a |
|
112 | - * relative path to append to the base path of the client. The URL can |
|
113 | - * contain the query string as well. |
|
114 | - * |
|
115 | - * @param string|UriInterface $uri URI object or string. |
|
116 | - * @param array $options Request options to apply. |
|
117 | - * |
|
118 | - * @throws GuzzleException |
|
119 | - */ |
|
120 | - public function delete($uri, array $options = []) : ResponseInterface |
|
121 | - { |
|
122 | - return $this->request('DELETE', $uri, $options); |
|
123 | - } |
|
124 | - /** |
|
125 | - * Create and send an asynchronous HTTP request. |
|
126 | - * |
|
127 | - * Use an absolute path to override the base path of the client, or a |
|
128 | - * relative path to append to the base path of the client. The URL can |
|
129 | - * contain the query string as well. Use an array to provide a URL |
|
130 | - * template and additional variables to use in the URL template expansion. |
|
131 | - * |
|
132 | - * @param string $method HTTP method |
|
133 | - * @param string|UriInterface $uri URI object or string. |
|
134 | - * @param array $options Request options to apply. |
|
135 | - */ |
|
136 | - public abstract function requestAsync(string $method, $uri, array $options = []) : PromiseInterface; |
|
137 | - /** |
|
138 | - * Create and send an asynchronous HTTP GET request. |
|
139 | - * |
|
140 | - * Use an absolute path to override the base path of the client, or a |
|
141 | - * relative path to append to the base path of the client. The URL can |
|
142 | - * contain the query string as well. Use an array to provide a URL |
|
143 | - * template and additional variables to use in the URL template expansion. |
|
144 | - * |
|
145 | - * @param string|UriInterface $uri URI object or string. |
|
146 | - * @param array $options Request options to apply. |
|
147 | - */ |
|
148 | - public function getAsync($uri, array $options = []) : PromiseInterface |
|
149 | - { |
|
150 | - return $this->requestAsync('GET', $uri, $options); |
|
151 | - } |
|
152 | - /** |
|
153 | - * Create and send an asynchronous HTTP HEAD request. |
|
154 | - * |
|
155 | - * Use an absolute path to override the base path of the client, or a |
|
156 | - * relative path to append to the base path of the client. The URL can |
|
157 | - * contain the query string as well. Use an array to provide a URL |
|
158 | - * template and additional variables to use in the URL template expansion. |
|
159 | - * |
|
160 | - * @param string|UriInterface $uri URI object or string. |
|
161 | - * @param array $options Request options to apply. |
|
162 | - */ |
|
163 | - public function headAsync($uri, array $options = []) : PromiseInterface |
|
164 | - { |
|
165 | - return $this->requestAsync('HEAD', $uri, $options); |
|
166 | - } |
|
167 | - /** |
|
168 | - * Create and send an asynchronous HTTP PUT request. |
|
169 | - * |
|
170 | - * Use an absolute path to override the base path of the client, or a |
|
171 | - * relative path to append to the base path of the client. The URL can |
|
172 | - * contain the query string as well. Use an array to provide a URL |
|
173 | - * template and additional variables to use in the URL template expansion. |
|
174 | - * |
|
175 | - * @param string|UriInterface $uri URI object or string. |
|
176 | - * @param array $options Request options to apply. |
|
177 | - */ |
|
178 | - public function putAsync($uri, array $options = []) : PromiseInterface |
|
179 | - { |
|
180 | - return $this->requestAsync('PUT', $uri, $options); |
|
181 | - } |
|
182 | - /** |
|
183 | - * Create and send an asynchronous HTTP POST request. |
|
184 | - * |
|
185 | - * Use an absolute path to override the base path of the client, or a |
|
186 | - * relative path to append to the base path of the client. The URL can |
|
187 | - * contain the query string as well. Use an array to provide a URL |
|
188 | - * template and additional variables to use in the URL template expansion. |
|
189 | - * |
|
190 | - * @param string|UriInterface $uri URI object or string. |
|
191 | - * @param array $options Request options to apply. |
|
192 | - */ |
|
193 | - public function postAsync($uri, array $options = []) : PromiseInterface |
|
194 | - { |
|
195 | - return $this->requestAsync('POST', $uri, $options); |
|
196 | - } |
|
197 | - /** |
|
198 | - * Create and send an asynchronous HTTP PATCH request. |
|
199 | - * |
|
200 | - * Use an absolute path to override the base path of the client, or a |
|
201 | - * relative path to append to the base path of the client. The URL can |
|
202 | - * contain the query string as well. Use an array to provide a URL |
|
203 | - * template and additional variables to use in the URL template expansion. |
|
204 | - * |
|
205 | - * @param string|UriInterface $uri URI object or string. |
|
206 | - * @param array $options Request options to apply. |
|
207 | - */ |
|
208 | - public function patchAsync($uri, array $options = []) : PromiseInterface |
|
209 | - { |
|
210 | - return $this->requestAsync('PATCH', $uri, $options); |
|
211 | - } |
|
212 | - /** |
|
213 | - * Create and send an asynchronous HTTP DELETE request. |
|
214 | - * |
|
215 | - * Use an absolute path to override the base path of the client, or a |
|
216 | - * relative path to append to the base path of the client. The URL can |
|
217 | - * contain the query string as well. Use an array to provide a URL |
|
218 | - * template and additional variables to use in the URL template expansion. |
|
219 | - * |
|
220 | - * @param string|UriInterface $uri URI object or string. |
|
221 | - * @param array $options Request options to apply. |
|
222 | - */ |
|
223 | - public function deleteAsync($uri, array $options = []) : PromiseInterface |
|
224 | - { |
|
225 | - return $this->requestAsync('DELETE', $uri, $options); |
|
226 | - } |
|
14 | + /** |
|
15 | + * Create and send an HTTP request. |
|
16 | + * |
|
17 | + * Use an absolute path to override the base path of the client, or a |
|
18 | + * relative path to append to the base path of the client. The URL can |
|
19 | + * contain the query string as well. |
|
20 | + * |
|
21 | + * @param string $method HTTP method. |
|
22 | + * @param string|UriInterface $uri URI object or string. |
|
23 | + * @param array $options Request options to apply. |
|
24 | + * |
|
25 | + * @throws GuzzleException |
|
26 | + */ |
|
27 | + public abstract function request(string $method, $uri, array $options = []) : ResponseInterface; |
|
28 | + /** |
|
29 | + * Create and send an HTTP GET request. |
|
30 | + * |
|
31 | + * Use an absolute path to override the base path of the client, or a |
|
32 | + * relative path to append to the base path of the client. The URL can |
|
33 | + * contain the query string as well. |
|
34 | + * |
|
35 | + * @param string|UriInterface $uri URI object or string. |
|
36 | + * @param array $options Request options to apply. |
|
37 | + * |
|
38 | + * @throws GuzzleException |
|
39 | + */ |
|
40 | + public function get($uri, array $options = []) : ResponseInterface |
|
41 | + { |
|
42 | + return $this->request('GET', $uri, $options); |
|
43 | + } |
|
44 | + /** |
|
45 | + * Create and send an HTTP HEAD request. |
|
46 | + * |
|
47 | + * Use an absolute path to override the base path of the client, or a |
|
48 | + * relative path to append to the base path of the client. The URL can |
|
49 | + * contain the query string as well. |
|
50 | + * |
|
51 | + * @param string|UriInterface $uri URI object or string. |
|
52 | + * @param array $options Request options to apply. |
|
53 | + * |
|
54 | + * @throws GuzzleException |
|
55 | + */ |
|
56 | + public function head($uri, array $options = []) : ResponseInterface |
|
57 | + { |
|
58 | + return $this->request('HEAD', $uri, $options); |
|
59 | + } |
|
60 | + /** |
|
61 | + * Create and send an HTTP PUT request. |
|
62 | + * |
|
63 | + * Use an absolute path to override the base path of the client, or a |
|
64 | + * relative path to append to the base path of the client. The URL can |
|
65 | + * contain the query string as well. |
|
66 | + * |
|
67 | + * @param string|UriInterface $uri URI object or string. |
|
68 | + * @param array $options Request options to apply. |
|
69 | + * |
|
70 | + * @throws GuzzleException |
|
71 | + */ |
|
72 | + public function put($uri, array $options = []) : ResponseInterface |
|
73 | + { |
|
74 | + return $this->request('PUT', $uri, $options); |
|
75 | + } |
|
76 | + /** |
|
77 | + * Create and send an HTTP POST request. |
|
78 | + * |
|
79 | + * Use an absolute path to override the base path of the client, or a |
|
80 | + * relative path to append to the base path of the client. The URL can |
|
81 | + * contain the query string as well. |
|
82 | + * |
|
83 | + * @param string|UriInterface $uri URI object or string. |
|
84 | + * @param array $options Request options to apply. |
|
85 | + * |
|
86 | + * @throws GuzzleException |
|
87 | + */ |
|
88 | + public function post($uri, array $options = []) : ResponseInterface |
|
89 | + { |
|
90 | + return $this->request('POST', $uri, $options); |
|
91 | + } |
|
92 | + /** |
|
93 | + * Create and send an HTTP PATCH request. |
|
94 | + * |
|
95 | + * Use an absolute path to override the base path of the client, or a |
|
96 | + * relative path to append to the base path of the client. The URL can |
|
97 | + * contain the query string as well. |
|
98 | + * |
|
99 | + * @param string|UriInterface $uri URI object or string. |
|
100 | + * @param array $options Request options to apply. |
|
101 | + * |
|
102 | + * @throws GuzzleException |
|
103 | + */ |
|
104 | + public function patch($uri, array $options = []) : ResponseInterface |
|
105 | + { |
|
106 | + return $this->request('PATCH', $uri, $options); |
|
107 | + } |
|
108 | + /** |
|
109 | + * Create and send an HTTP DELETE request. |
|
110 | + * |
|
111 | + * Use an absolute path to override the base path of the client, or a |
|
112 | + * relative path to append to the base path of the client. The URL can |
|
113 | + * contain the query string as well. |
|
114 | + * |
|
115 | + * @param string|UriInterface $uri URI object or string. |
|
116 | + * @param array $options Request options to apply. |
|
117 | + * |
|
118 | + * @throws GuzzleException |
|
119 | + */ |
|
120 | + public function delete($uri, array $options = []) : ResponseInterface |
|
121 | + { |
|
122 | + return $this->request('DELETE', $uri, $options); |
|
123 | + } |
|
124 | + /** |
|
125 | + * Create and send an asynchronous HTTP request. |
|
126 | + * |
|
127 | + * Use an absolute path to override the base path of the client, or a |
|
128 | + * relative path to append to the base path of the client. The URL can |
|
129 | + * contain the query string as well. Use an array to provide a URL |
|
130 | + * template and additional variables to use in the URL template expansion. |
|
131 | + * |
|
132 | + * @param string $method HTTP method |
|
133 | + * @param string|UriInterface $uri URI object or string. |
|
134 | + * @param array $options Request options to apply. |
|
135 | + */ |
|
136 | + public abstract function requestAsync(string $method, $uri, array $options = []) : PromiseInterface; |
|
137 | + /** |
|
138 | + * Create and send an asynchronous HTTP GET request. |
|
139 | + * |
|
140 | + * Use an absolute path to override the base path of the client, or a |
|
141 | + * relative path to append to the base path of the client. The URL can |
|
142 | + * contain the query string as well. Use an array to provide a URL |
|
143 | + * template and additional variables to use in the URL template expansion. |
|
144 | + * |
|
145 | + * @param string|UriInterface $uri URI object or string. |
|
146 | + * @param array $options Request options to apply. |
|
147 | + */ |
|
148 | + public function getAsync($uri, array $options = []) : PromiseInterface |
|
149 | + { |
|
150 | + return $this->requestAsync('GET', $uri, $options); |
|
151 | + } |
|
152 | + /** |
|
153 | + * Create and send an asynchronous HTTP HEAD request. |
|
154 | + * |
|
155 | + * Use an absolute path to override the base path of the client, or a |
|
156 | + * relative path to append to the base path of the client. The URL can |
|
157 | + * contain the query string as well. Use an array to provide a URL |
|
158 | + * template and additional variables to use in the URL template expansion. |
|
159 | + * |
|
160 | + * @param string|UriInterface $uri URI object or string. |
|
161 | + * @param array $options Request options to apply. |
|
162 | + */ |
|
163 | + public function headAsync($uri, array $options = []) : PromiseInterface |
|
164 | + { |
|
165 | + return $this->requestAsync('HEAD', $uri, $options); |
|
166 | + } |
|
167 | + /** |
|
168 | + * Create and send an asynchronous HTTP PUT request. |
|
169 | + * |
|
170 | + * Use an absolute path to override the base path of the client, or a |
|
171 | + * relative path to append to the base path of the client. The URL can |
|
172 | + * contain the query string as well. Use an array to provide a URL |
|
173 | + * template and additional variables to use in the URL template expansion. |
|
174 | + * |
|
175 | + * @param string|UriInterface $uri URI object or string. |
|
176 | + * @param array $options Request options to apply. |
|
177 | + */ |
|
178 | + public function putAsync($uri, array $options = []) : PromiseInterface |
|
179 | + { |
|
180 | + return $this->requestAsync('PUT', $uri, $options); |
|
181 | + } |
|
182 | + /** |
|
183 | + * Create and send an asynchronous HTTP POST request. |
|
184 | + * |
|
185 | + * Use an absolute path to override the base path of the client, or a |
|
186 | + * relative path to append to the base path of the client. The URL can |
|
187 | + * contain the query string as well. Use an array to provide a URL |
|
188 | + * template and additional variables to use in the URL template expansion. |
|
189 | + * |
|
190 | + * @param string|UriInterface $uri URI object or string. |
|
191 | + * @param array $options Request options to apply. |
|
192 | + */ |
|
193 | + public function postAsync($uri, array $options = []) : PromiseInterface |
|
194 | + { |
|
195 | + return $this->requestAsync('POST', $uri, $options); |
|
196 | + } |
|
197 | + /** |
|
198 | + * Create and send an asynchronous HTTP PATCH request. |
|
199 | + * |
|
200 | + * Use an absolute path to override the base path of the client, or a |
|
201 | + * relative path to append to the base path of the client. The URL can |
|
202 | + * contain the query string as well. Use an array to provide a URL |
|
203 | + * template and additional variables to use in the URL template expansion. |
|
204 | + * |
|
205 | + * @param string|UriInterface $uri URI object or string. |
|
206 | + * @param array $options Request options to apply. |
|
207 | + */ |
|
208 | + public function patchAsync($uri, array $options = []) : PromiseInterface |
|
209 | + { |
|
210 | + return $this->requestAsync('PATCH', $uri, $options); |
|
211 | + } |
|
212 | + /** |
|
213 | + * Create and send an asynchronous HTTP DELETE request. |
|
214 | + * |
|
215 | + * Use an absolute path to override the base path of the client, or a |
|
216 | + * relative path to append to the base path of the client. The URL can |
|
217 | + * contain the query string as well. Use an array to provide a URL |
|
218 | + * template and additional variables to use in the URL template expansion. |
|
219 | + * |
|
220 | + * @param string|UriInterface $uri URI object or string. |
|
221 | + * @param array $options Request options to apply. |
|
222 | + */ |
|
223 | + public function deleteAsync($uri, array $options = []) : PromiseInterface |
|
224 | + { |
|
225 | + return $this->requestAsync('DELETE', $uri, $options); |
|
226 | + } |
|
227 | 227 | } |
@@ -11,8 +11,7 @@ |
||
11 | 11 | /** |
12 | 12 | * Client interface for sending HTTP requests. |
13 | 13 | */ |
14 | -interface ClientInterface |
|
15 | -{ |
|
14 | +interface ClientInterface { |
|
16 | 15 | /** |
17 | 16 | * The Guzzle major version. |
18 | 17 | */ |
@@ -12,67 +12,67 @@ |
||
12 | 12 | */ |
13 | 13 | interface ClientInterface |
14 | 14 | { |
15 | - /** |
|
16 | - * The Guzzle major version. |
|
17 | - */ |
|
18 | - public const MAJOR_VERSION = 7; |
|
19 | - /** |
|
20 | - * Send an HTTP request. |
|
21 | - * |
|
22 | - * @param RequestInterface $request Request to send |
|
23 | - * @param array $options Request options to apply to the given |
|
24 | - * request and to the transfer. |
|
25 | - * |
|
26 | - * @throws GuzzleException |
|
27 | - */ |
|
28 | - public function send(RequestInterface $request, array $options = []) : ResponseInterface; |
|
29 | - /** |
|
30 | - * Asynchronously send an HTTP request. |
|
31 | - * |
|
32 | - * @param RequestInterface $request Request to send |
|
33 | - * @param array $options Request options to apply to the given |
|
34 | - * request and to the transfer. |
|
35 | - */ |
|
36 | - public function sendAsync(RequestInterface $request, array $options = []) : PromiseInterface; |
|
37 | - /** |
|
38 | - * Create and send an HTTP request. |
|
39 | - * |
|
40 | - * Use an absolute path to override the base path of the client, or a |
|
41 | - * relative path to append to the base path of the client. The URL can |
|
42 | - * contain the query string as well. |
|
43 | - * |
|
44 | - * @param string $method HTTP method. |
|
45 | - * @param string|UriInterface $uri URI object or string. |
|
46 | - * @param array $options Request options to apply. |
|
47 | - * |
|
48 | - * @throws GuzzleException |
|
49 | - */ |
|
50 | - public function request(string $method, $uri, array $options = []) : ResponseInterface; |
|
51 | - /** |
|
52 | - * Create and send an asynchronous HTTP request. |
|
53 | - * |
|
54 | - * Use an absolute path to override the base path of the client, or a |
|
55 | - * relative path to append to the base path of the client. The URL can |
|
56 | - * contain the query string as well. Use an array to provide a URL |
|
57 | - * template and additional variables to use in the URL template expansion. |
|
58 | - * |
|
59 | - * @param string $method HTTP method |
|
60 | - * @param string|UriInterface $uri URI object or string. |
|
61 | - * @param array $options Request options to apply. |
|
62 | - */ |
|
63 | - public function requestAsync(string $method, $uri, array $options = []) : PromiseInterface; |
|
64 | - /** |
|
65 | - * Get a client configuration option. |
|
66 | - * |
|
67 | - * These options include default request options of the client, a "handler" |
|
68 | - * (if utilized by the concrete client), and a "base_uri" if utilized by |
|
69 | - * the concrete client. |
|
70 | - * |
|
71 | - * @param string|null $option The config option to retrieve. |
|
72 | - * |
|
73 | - * @return mixed |
|
74 | - * |
|
75 | - * @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0. |
|
76 | - */ |
|
77 | - public function getConfig(string $option = null); |
|
15 | + /** |
|
16 | + * The Guzzle major version. |
|
17 | + */ |
|
18 | + public const MAJOR_VERSION = 7; |
|
19 | + /** |
|
20 | + * Send an HTTP request. |
|
21 | + * |
|
22 | + * @param RequestInterface $request Request to send |
|
23 | + * @param array $options Request options to apply to the given |
|
24 | + * request and to the transfer. |
|
25 | + * |
|
26 | + * @throws GuzzleException |
|
27 | + */ |
|
28 | + public function send(RequestInterface $request, array $options = []) : ResponseInterface; |
|
29 | + /** |
|
30 | + * Asynchronously send an HTTP request. |
|
31 | + * |
|
32 | + * @param RequestInterface $request Request to send |
|
33 | + * @param array $options Request options to apply to the given |
|
34 | + * request and to the transfer. |
|
35 | + */ |
|
36 | + public function sendAsync(RequestInterface $request, array $options = []) : PromiseInterface; |
|
37 | + /** |
|
38 | + * Create and send an HTTP request. |
|
39 | + * |
|
40 | + * Use an absolute path to override the base path of the client, or a |
|
41 | + * relative path to append to the base path of the client. The URL can |
|
42 | + * contain the query string as well. |
|
43 | + * |
|
44 | + * @param string $method HTTP method. |
|
45 | + * @param string|UriInterface $uri URI object or string. |
|
46 | + * @param array $options Request options to apply. |
|
47 | + * |
|
48 | + * @throws GuzzleException |
|
49 | + */ |
|
50 | + public function request(string $method, $uri, array $options = []) : ResponseInterface; |
|
51 | + /** |
|
52 | + * Create and send an asynchronous HTTP request. |
|
53 | + * |
|
54 | + * Use an absolute path to override the base path of the client, or a |
|
55 | + * relative path to append to the base path of the client. The URL can |
|
56 | + * contain the query string as well. Use an array to provide a URL |
|
57 | + * template and additional variables to use in the URL template expansion. |
|
58 | + * |
|
59 | + * @param string $method HTTP method |
|
60 | + * @param string|UriInterface $uri URI object or string. |
|
61 | + * @param array $options Request options to apply. |
|
62 | + */ |
|
63 | + public function requestAsync(string $method, $uri, array $options = []) : PromiseInterface; |
|
64 | + /** |
|
65 | + * Get a client configuration option. |
|
66 | + * |
|
67 | + * These options include default request options of the client, a "handler" |
|
68 | + * (if utilized by the concrete client), and a "base_uri" if utilized by |
|
69 | + * the concrete client. |
|
70 | + * |
|
71 | + * @param string|null $option The config option to retrieve. |
|
72 | + * |
|
73 | + * @return mixed |
|
74 | + * |
|
75 | + * @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0. |
|
76 | + */ |
|
77 | + public function getConfig(string $option = null); |
|
78 | 78 | } |
@@ -20,8 +20,7 @@ |
||
20 | 20 | * |
21 | 21 | * @final |
22 | 22 | */ |
23 | -class StreamHandler |
|
24 | -{ |
|
23 | +class StreamHandler { |
|
25 | 24 | /** |
26 | 25 | * @var array |
27 | 26 | */ |
@@ -21,435 +21,435 @@ |
||
21 | 21 | */ |
22 | 22 | class StreamHandler |
23 | 23 | { |
24 | - /** |
|
25 | - * @var array |
|
26 | - */ |
|
27 | - private $lastHeaders = []; |
|
28 | - /** |
|
29 | - * Sends an HTTP request. |
|
30 | - * |
|
31 | - * @param RequestInterface $request Request to send. |
|
32 | - * @param array $options Request transfer options. |
|
33 | - */ |
|
34 | - public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
35 | - { |
|
36 | - // Sleep if there is a delay specified. |
|
37 | - if (isset($options['delay'])) { |
|
38 | - \usleep($options['delay'] * 1000); |
|
39 | - } |
|
40 | - $startTime = isset($options['on_stats']) ? Utils::currentTime() : null; |
|
41 | - try { |
|
42 | - // Does not support the expect header. |
|
43 | - $request = $request->withoutHeader('Expect'); |
|
44 | - // Append a content-length header if body size is zero to match |
|
45 | - // cURL's behavior. |
|
46 | - if (0 === $request->getBody()->getSize()) { |
|
47 | - $request = $request->withHeader('Content-Length', '0'); |
|
48 | - } |
|
49 | - return $this->createResponse($request, $options, $this->createStream($request, $options), $startTime); |
|
50 | - } catch (\InvalidArgumentException $e) { |
|
51 | - throw $e; |
|
52 | - } catch (\Exception $e) { |
|
53 | - // Determine if the error was a networking error. |
|
54 | - $message = $e->getMessage(); |
|
55 | - // This list can probably get more comprehensive. |
|
56 | - if (\false !== \strpos($message, 'getaddrinfo') || \false !== \strpos($message, 'Connection refused') || \false !== \strpos($message, "couldn't connect to host") || \false !== \strpos($message, 'connection attempt failed')) { |
|
57 | - $e = new ConnectException($e->getMessage(), $request, $e); |
|
58 | - } else { |
|
59 | - $e = RequestException::wrapException($request, $e); |
|
60 | - } |
|
61 | - $this->invokeStats($options, $request, $startTime, null, $e); |
|
62 | - return P\Create::rejectionFor($e); |
|
63 | - } |
|
64 | - } |
|
65 | - private function invokeStats(array $options, RequestInterface $request, ?float $startTime, ResponseInterface $response = null, \Throwable $error = null) : void |
|
66 | - { |
|
67 | - if (isset($options['on_stats'])) { |
|
68 | - $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); |
|
69 | - $options['on_stats']($stats); |
|
70 | - } |
|
71 | - } |
|
72 | - /** |
|
73 | - * @param resource $stream |
|
74 | - */ |
|
75 | - private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime) : PromiseInterface |
|
76 | - { |
|
77 | - $hdrs = $this->lastHeaders; |
|
78 | - $this->lastHeaders = []; |
|
79 | - try { |
|
80 | - [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); |
|
81 | - } catch (\Exception $e) { |
|
82 | - return P\Create::rejectionFor(new RequestException('An error was encountered while creating the response', $request, null, $e)); |
|
83 | - } |
|
84 | - [$stream, $headers] = $this->checkDecode($options, $headers, $stream); |
|
85 | - $stream = Psr7\Utils::streamFor($stream); |
|
86 | - $sink = $stream; |
|
87 | - if (\strcasecmp('HEAD', $request->getMethod())) { |
|
88 | - $sink = $this->createSink($stream, $options); |
|
89 | - } |
|
90 | - try { |
|
91 | - $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); |
|
92 | - } catch (\Exception $e) { |
|
93 | - return P\Create::rejectionFor(new RequestException('An error was encountered while creating the response', $request, null, $e)); |
|
94 | - } |
|
95 | - if (isset($options['on_headers'])) { |
|
96 | - try { |
|
97 | - $options['on_headers']($response); |
|
98 | - } catch (\Exception $e) { |
|
99 | - return P\Create::rejectionFor(new RequestException('An error was encountered during the on_headers event', $request, $response, $e)); |
|
100 | - } |
|
101 | - } |
|
102 | - // Do not drain when the request is a HEAD request because they have |
|
103 | - // no body. |
|
104 | - if ($sink !== $stream) { |
|
105 | - $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); |
|
106 | - } |
|
107 | - $this->invokeStats($options, $request, $startTime, $response, null); |
|
108 | - return new FulfilledPromise($response); |
|
109 | - } |
|
110 | - private function createSink(StreamInterface $stream, array $options) : StreamInterface |
|
111 | - { |
|
112 | - if (!empty($options['stream'])) { |
|
113 | - return $stream; |
|
114 | - } |
|
115 | - $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); |
|
116 | - return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); |
|
117 | - } |
|
118 | - /** |
|
119 | - * @param resource $stream |
|
120 | - */ |
|
121 | - private function checkDecode(array $options, array $headers, $stream) : array |
|
122 | - { |
|
123 | - // Automatically decode responses when instructed. |
|
124 | - if (!empty($options['decode_content'])) { |
|
125 | - $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
126 | - if (isset($normalizedKeys['content-encoding'])) { |
|
127 | - $encoding = $headers[$normalizedKeys['content-encoding']]; |
|
128 | - if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { |
|
129 | - $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); |
|
130 | - $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
131 | - // Remove content-encoding header |
|
132 | - unset($headers[$normalizedKeys['content-encoding']]); |
|
133 | - // Fix content-length header |
|
134 | - if (isset($normalizedKeys['content-length'])) { |
|
135 | - $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
136 | - $length = (int) $stream->getSize(); |
|
137 | - if ($length === 0) { |
|
138 | - unset($headers[$normalizedKeys['content-length']]); |
|
139 | - } else { |
|
140 | - $headers[$normalizedKeys['content-length']] = [$length]; |
|
141 | - } |
|
142 | - } |
|
143 | - } |
|
144 | - } |
|
145 | - } |
|
146 | - return [$stream, $headers]; |
|
147 | - } |
|
148 | - /** |
|
149 | - * Drains the source stream into the "sink" client option. |
|
150 | - * |
|
151 | - * @param string $contentLength Header specifying the amount of |
|
152 | - * data to read. |
|
153 | - * |
|
154 | - * @throws \RuntimeException when the sink option is invalid. |
|
155 | - */ |
|
156 | - private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength) : StreamInterface |
|
157 | - { |
|
158 | - // If a content-length header is provided, then stop reading once |
|
159 | - // that number of bytes has been read. This can prevent infinitely |
|
160 | - // reading from a stream when dealing with servers that do not honor |
|
161 | - // Connection: Close headers. |
|
162 | - Psr7\Utils::copyToStream($source, $sink, \strlen($contentLength) > 0 && (int) $contentLength > 0 ? (int) $contentLength : -1); |
|
163 | - $sink->seek(0); |
|
164 | - $source->close(); |
|
165 | - return $sink; |
|
166 | - } |
|
167 | - /** |
|
168 | - * Create a resource and check to ensure it was created successfully |
|
169 | - * |
|
170 | - * @param callable $callback Callable that returns stream resource |
|
171 | - * |
|
172 | - * @return resource |
|
173 | - * |
|
174 | - * @throws \RuntimeException on error |
|
175 | - */ |
|
176 | - private function createResource(callable $callback) |
|
177 | - { |
|
178 | - $errors = []; |
|
179 | - \set_error_handler(static function ($_, $msg, $file, $line) use(&$errors) : bool { |
|
180 | - $errors[] = ['message' => $msg, 'file' => $file, 'line' => $line]; |
|
181 | - return \true; |
|
182 | - }); |
|
183 | - try { |
|
184 | - $resource = $callback(); |
|
185 | - } finally { |
|
186 | - \restore_error_handler(); |
|
187 | - } |
|
188 | - if (!$resource) { |
|
189 | - $message = 'Error creating resource: '; |
|
190 | - foreach ($errors as $err) { |
|
191 | - foreach ($err as $key => $value) { |
|
192 | - $message .= "[{$key}] {$value}" . \PHP_EOL; |
|
193 | - } |
|
194 | - } |
|
195 | - throw new \RuntimeException(\trim($message)); |
|
196 | - } |
|
197 | - return $resource; |
|
198 | - } |
|
199 | - /** |
|
200 | - * @return resource |
|
201 | - */ |
|
202 | - private function createStream(RequestInterface $request, array $options) |
|
203 | - { |
|
204 | - static $methods; |
|
205 | - if (!$methods) { |
|
206 | - $methods = \array_flip(\get_class_methods(__CLASS__)); |
|
207 | - } |
|
208 | - if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { |
|
209 | - throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); |
|
210 | - } |
|
211 | - // HTTP/1.1 streams using the PHP stream wrapper require a |
|
212 | - // Connection: close header |
|
213 | - if ($request->getProtocolVersion() == '1.1' && !$request->hasHeader('Connection')) { |
|
214 | - $request = $request->withHeader('Connection', 'close'); |
|
215 | - } |
|
216 | - // Ensure SSL is verified by default |
|
217 | - if (!isset($options['verify'])) { |
|
218 | - $options['verify'] = \true; |
|
219 | - } |
|
220 | - $params = []; |
|
221 | - $context = $this->getDefaultContext($request); |
|
222 | - if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { |
|
223 | - throw new \InvalidArgumentException('on_headers must be callable'); |
|
224 | - } |
|
225 | - if (!empty($options)) { |
|
226 | - foreach ($options as $key => $value) { |
|
227 | - $method = "add_{$key}"; |
|
228 | - if (isset($methods[$method])) { |
|
229 | - $this->{$method}($request, $context, $value, $params); |
|
230 | - } |
|
231 | - } |
|
232 | - } |
|
233 | - if (isset($options['stream_context'])) { |
|
234 | - if (!\is_array($options['stream_context'])) { |
|
235 | - throw new \InvalidArgumentException('stream_context must be an array'); |
|
236 | - } |
|
237 | - $context = \array_replace_recursive($context, $options['stream_context']); |
|
238 | - } |
|
239 | - // Microsoft NTLM authentication only supported with curl handler |
|
240 | - if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { |
|
241 | - throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); |
|
242 | - } |
|
243 | - $uri = $this->resolveHost($request, $options); |
|
244 | - $contextResource = $this->createResource(static function () use($context, $params) { |
|
245 | - return \stream_context_create($context, $params); |
|
246 | - }); |
|
247 | - return $this->createResource(function () use($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
248 | - $resource = @\fopen((string) $uri, 'r', \false, $contextResource); |
|
249 | - $this->lastHeaders = $http_response_header ?? []; |
|
250 | - if (\false === $resource) { |
|
251 | - throw new ConnectException(\sprintf('Connection refused for URI %s', $uri), $request, null, $context); |
|
252 | - } |
|
253 | - if (isset($options['read_timeout'])) { |
|
254 | - $readTimeout = $options['read_timeout']; |
|
255 | - $sec = (int) $readTimeout; |
|
256 | - $usec = ($readTimeout - $sec) * 100000; |
|
257 | - \stream_set_timeout($resource, $sec, $usec); |
|
258 | - } |
|
259 | - return $resource; |
|
260 | - }); |
|
261 | - } |
|
262 | - private function resolveHost(RequestInterface $request, array $options) : UriInterface |
|
263 | - { |
|
264 | - $uri = $request->getUri(); |
|
265 | - if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { |
|
266 | - if ('v4' === $options['force_ip_resolve']) { |
|
267 | - $records = \dns_get_record($uri->getHost(), \DNS_A); |
|
268 | - if (\false === $records || !isset($records[0]['ip'])) { |
|
269 | - throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); |
|
270 | - } |
|
271 | - return $uri->withHost($records[0]['ip']); |
|
272 | - } |
|
273 | - if ('v6' === $options['force_ip_resolve']) { |
|
274 | - $records = \dns_get_record($uri->getHost(), \DNS_AAAA); |
|
275 | - if (\false === $records || !isset($records[0]['ipv6'])) { |
|
276 | - throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); |
|
277 | - } |
|
278 | - return $uri->withHost('[' . $records[0]['ipv6'] . ']'); |
|
279 | - } |
|
280 | - } |
|
281 | - return $uri; |
|
282 | - } |
|
283 | - private function getDefaultContext(RequestInterface $request) : array |
|
284 | - { |
|
285 | - $headers = ''; |
|
286 | - foreach ($request->getHeaders() as $name => $value) { |
|
287 | - foreach ($value as $val) { |
|
288 | - $headers .= "{$name}: {$val}\r\n"; |
|
289 | - } |
|
290 | - } |
|
291 | - $context = ['http' => ['method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => \true, 'follow_location' => 0], 'ssl' => ['peer_name' => $request->getUri()->getHost()]]; |
|
292 | - $body = (string) $request->getBody(); |
|
293 | - if ('' !== $body) { |
|
294 | - $context['http']['content'] = $body; |
|
295 | - // Prevent the HTTP handler from adding a Content-Type header. |
|
296 | - if (!$request->hasHeader('Content-Type')) { |
|
297 | - $context['http']['header'] .= "Content-Type:\r\n"; |
|
298 | - } |
|
299 | - } |
|
300 | - $context['http']['header'] = \rtrim($context['http']['header']); |
|
301 | - return $context; |
|
302 | - } |
|
303 | - /** |
|
304 | - * @param mixed $value as passed via Request transfer options. |
|
305 | - */ |
|
306 | - private function add_proxy(RequestInterface $request, array &$options, $value, array &$params) : void |
|
307 | - { |
|
308 | - $uri = null; |
|
309 | - if (!\is_array($value)) { |
|
310 | - $uri = $value; |
|
311 | - } else { |
|
312 | - $scheme = $request->getUri()->getScheme(); |
|
313 | - if (isset($value[$scheme])) { |
|
314 | - if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { |
|
315 | - $uri = $value[$scheme]; |
|
316 | - } |
|
317 | - } |
|
318 | - } |
|
319 | - if (!$uri) { |
|
320 | - return; |
|
321 | - } |
|
322 | - $parsed = $this->parse_proxy($uri); |
|
323 | - $options['http']['proxy'] = $parsed['proxy']; |
|
324 | - if ($parsed['auth']) { |
|
325 | - if (!isset($options['http']['header'])) { |
|
326 | - $options['http']['header'] = []; |
|
327 | - } |
|
328 | - $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; |
|
329 | - } |
|
330 | - } |
|
331 | - /** |
|
332 | - * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. |
|
333 | - */ |
|
334 | - private function parse_proxy(string $url) : array |
|
335 | - { |
|
336 | - $parsed = \parse_url($url); |
|
337 | - if ($parsed !== \false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { |
|
338 | - if (isset($parsed['host']) && isset($parsed['port'])) { |
|
339 | - $auth = null; |
|
340 | - if (isset($parsed['user']) && isset($parsed['pass'])) { |
|
341 | - $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); |
|
342 | - } |
|
343 | - return ['proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", 'auth' => $auth ? "Basic {$auth}" : null]; |
|
344 | - } |
|
345 | - } |
|
346 | - // Return proxy as-is. |
|
347 | - return ['proxy' => $url, 'auth' => null]; |
|
348 | - } |
|
349 | - /** |
|
350 | - * @param mixed $value as passed via Request transfer options. |
|
351 | - */ |
|
352 | - private function add_timeout(RequestInterface $request, array &$options, $value, array &$params) : void |
|
353 | - { |
|
354 | - if ($value > 0) { |
|
355 | - $options['http']['timeout'] = $value; |
|
356 | - } |
|
357 | - } |
|
358 | - /** |
|
359 | - * @param mixed $value as passed via Request transfer options. |
|
360 | - */ |
|
361 | - private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params) : void |
|
362 | - { |
|
363 | - if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT || \defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) { |
|
364 | - $options['http']['crypto_method'] = $value; |
|
365 | - return; |
|
366 | - } |
|
367 | - throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); |
|
368 | - } |
|
369 | - /** |
|
370 | - * @param mixed $value as passed via Request transfer options. |
|
371 | - */ |
|
372 | - private function add_verify(RequestInterface $request, array &$options, $value, array &$params) : void |
|
373 | - { |
|
374 | - if ($value === \false) { |
|
375 | - $options['ssl']['verify_peer'] = \false; |
|
376 | - $options['ssl']['verify_peer_name'] = \false; |
|
377 | - return; |
|
378 | - } |
|
379 | - if (\is_string($value)) { |
|
380 | - $options['ssl']['cafile'] = $value; |
|
381 | - if (!\file_exists($value)) { |
|
382 | - throw new \RuntimeException("SSL CA bundle not found: {$value}"); |
|
383 | - } |
|
384 | - } elseif ($value !== \true) { |
|
385 | - throw new \InvalidArgumentException('Invalid verify request option'); |
|
386 | - } |
|
387 | - $options['ssl']['verify_peer'] = \true; |
|
388 | - $options['ssl']['verify_peer_name'] = \true; |
|
389 | - $options['ssl']['allow_self_signed'] = \false; |
|
390 | - } |
|
391 | - /** |
|
392 | - * @param mixed $value as passed via Request transfer options. |
|
393 | - */ |
|
394 | - private function add_cert(RequestInterface $request, array &$options, $value, array &$params) : void |
|
395 | - { |
|
396 | - if (\is_array($value)) { |
|
397 | - $options['ssl']['passphrase'] = $value[1]; |
|
398 | - $value = $value[0]; |
|
399 | - } |
|
400 | - if (!\file_exists($value)) { |
|
401 | - throw new \RuntimeException("SSL certificate not found: {$value}"); |
|
402 | - } |
|
403 | - $options['ssl']['local_cert'] = $value; |
|
404 | - } |
|
405 | - /** |
|
406 | - * @param mixed $value as passed via Request transfer options. |
|
407 | - */ |
|
408 | - private function add_progress(RequestInterface $request, array &$options, $value, array &$params) : void |
|
409 | - { |
|
410 | - self::addNotification($params, static function ($code, $a, $b, $c, $transferred, $total) use($value) { |
|
411 | - if ($code == \STREAM_NOTIFY_PROGRESS) { |
|
412 | - // The upload progress cannot be determined. Use 0 for cURL compatibility: |
|
413 | - // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
|
414 | - $value($total, $transferred, 0, 0); |
|
415 | - } |
|
416 | - }); |
|
417 | - } |
|
418 | - /** |
|
419 | - * @param mixed $value as passed via Request transfer options. |
|
420 | - */ |
|
421 | - private function add_debug(RequestInterface $request, array &$options, $value, array &$params) : void |
|
422 | - { |
|
423 | - if ($value === \false) { |
|
424 | - return; |
|
425 | - } |
|
426 | - static $map = [\STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', \STREAM_NOTIFY_PROGRESS => 'PROGRESS', \STREAM_NOTIFY_FAILURE => 'FAILURE', \STREAM_NOTIFY_COMPLETED => 'COMPLETED', \STREAM_NOTIFY_RESOLVE => 'RESOLVE']; |
|
427 | - static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; |
|
428 | - $value = Utils::debugResource($value); |
|
429 | - $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); |
|
430 | - self::addNotification($params, static function (int $code, ...$passed) use($ident, $value, $map, $args) : void { |
|
431 | - \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
|
432 | - foreach (\array_filter($passed) as $i => $v) { |
|
433 | - \fwrite($value, $args[$i] . ': "' . $v . '" '); |
|
434 | - } |
|
435 | - \fwrite($value, "\n"); |
|
436 | - }); |
|
437 | - } |
|
438 | - private static function addNotification(array &$params, callable $notify) : void |
|
439 | - { |
|
440 | - // Wrap the existing function if needed. |
|
441 | - if (!isset($params['notification'])) { |
|
442 | - $params['notification'] = $notify; |
|
443 | - } else { |
|
444 | - $params['notification'] = self::callArray([$params['notification'], $notify]); |
|
445 | - } |
|
446 | - } |
|
447 | - private static function callArray(array $functions) : callable |
|
448 | - { |
|
449 | - return static function (...$args) use($functions) { |
|
450 | - foreach ($functions as $fn) { |
|
451 | - $fn(...$args); |
|
452 | - } |
|
453 | - }; |
|
454 | - } |
|
24 | + /** |
|
25 | + * @var array |
|
26 | + */ |
|
27 | + private $lastHeaders = []; |
|
28 | + /** |
|
29 | + * Sends an HTTP request. |
|
30 | + * |
|
31 | + * @param RequestInterface $request Request to send. |
|
32 | + * @param array $options Request transfer options. |
|
33 | + */ |
|
34 | + public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
35 | + { |
|
36 | + // Sleep if there is a delay specified. |
|
37 | + if (isset($options['delay'])) { |
|
38 | + \usleep($options['delay'] * 1000); |
|
39 | + } |
|
40 | + $startTime = isset($options['on_stats']) ? Utils::currentTime() : null; |
|
41 | + try { |
|
42 | + // Does not support the expect header. |
|
43 | + $request = $request->withoutHeader('Expect'); |
|
44 | + // Append a content-length header if body size is zero to match |
|
45 | + // cURL's behavior. |
|
46 | + if (0 === $request->getBody()->getSize()) { |
|
47 | + $request = $request->withHeader('Content-Length', '0'); |
|
48 | + } |
|
49 | + return $this->createResponse($request, $options, $this->createStream($request, $options), $startTime); |
|
50 | + } catch (\InvalidArgumentException $e) { |
|
51 | + throw $e; |
|
52 | + } catch (\Exception $e) { |
|
53 | + // Determine if the error was a networking error. |
|
54 | + $message = $e->getMessage(); |
|
55 | + // This list can probably get more comprehensive. |
|
56 | + if (\false !== \strpos($message, 'getaddrinfo') || \false !== \strpos($message, 'Connection refused') || \false !== \strpos($message, "couldn't connect to host") || \false !== \strpos($message, 'connection attempt failed')) { |
|
57 | + $e = new ConnectException($e->getMessage(), $request, $e); |
|
58 | + } else { |
|
59 | + $e = RequestException::wrapException($request, $e); |
|
60 | + } |
|
61 | + $this->invokeStats($options, $request, $startTime, null, $e); |
|
62 | + return P\Create::rejectionFor($e); |
|
63 | + } |
|
64 | + } |
|
65 | + private function invokeStats(array $options, RequestInterface $request, ?float $startTime, ResponseInterface $response = null, \Throwable $error = null) : void |
|
66 | + { |
|
67 | + if (isset($options['on_stats'])) { |
|
68 | + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); |
|
69 | + $options['on_stats']($stats); |
|
70 | + } |
|
71 | + } |
|
72 | + /** |
|
73 | + * @param resource $stream |
|
74 | + */ |
|
75 | + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime) : PromiseInterface |
|
76 | + { |
|
77 | + $hdrs = $this->lastHeaders; |
|
78 | + $this->lastHeaders = []; |
|
79 | + try { |
|
80 | + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); |
|
81 | + } catch (\Exception $e) { |
|
82 | + return P\Create::rejectionFor(new RequestException('An error was encountered while creating the response', $request, null, $e)); |
|
83 | + } |
|
84 | + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); |
|
85 | + $stream = Psr7\Utils::streamFor($stream); |
|
86 | + $sink = $stream; |
|
87 | + if (\strcasecmp('HEAD', $request->getMethod())) { |
|
88 | + $sink = $this->createSink($stream, $options); |
|
89 | + } |
|
90 | + try { |
|
91 | + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); |
|
92 | + } catch (\Exception $e) { |
|
93 | + return P\Create::rejectionFor(new RequestException('An error was encountered while creating the response', $request, null, $e)); |
|
94 | + } |
|
95 | + if (isset($options['on_headers'])) { |
|
96 | + try { |
|
97 | + $options['on_headers']($response); |
|
98 | + } catch (\Exception $e) { |
|
99 | + return P\Create::rejectionFor(new RequestException('An error was encountered during the on_headers event', $request, $response, $e)); |
|
100 | + } |
|
101 | + } |
|
102 | + // Do not drain when the request is a HEAD request because they have |
|
103 | + // no body. |
|
104 | + if ($sink !== $stream) { |
|
105 | + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); |
|
106 | + } |
|
107 | + $this->invokeStats($options, $request, $startTime, $response, null); |
|
108 | + return new FulfilledPromise($response); |
|
109 | + } |
|
110 | + private function createSink(StreamInterface $stream, array $options) : StreamInterface |
|
111 | + { |
|
112 | + if (!empty($options['stream'])) { |
|
113 | + return $stream; |
|
114 | + } |
|
115 | + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); |
|
116 | + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); |
|
117 | + } |
|
118 | + /** |
|
119 | + * @param resource $stream |
|
120 | + */ |
|
121 | + private function checkDecode(array $options, array $headers, $stream) : array |
|
122 | + { |
|
123 | + // Automatically decode responses when instructed. |
|
124 | + if (!empty($options['decode_content'])) { |
|
125 | + $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
126 | + if (isset($normalizedKeys['content-encoding'])) { |
|
127 | + $encoding = $headers[$normalizedKeys['content-encoding']]; |
|
128 | + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { |
|
129 | + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); |
|
130 | + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
131 | + // Remove content-encoding header |
|
132 | + unset($headers[$normalizedKeys['content-encoding']]); |
|
133 | + // Fix content-length header |
|
134 | + if (isset($normalizedKeys['content-length'])) { |
|
135 | + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
136 | + $length = (int) $stream->getSize(); |
|
137 | + if ($length === 0) { |
|
138 | + unset($headers[$normalizedKeys['content-length']]); |
|
139 | + } else { |
|
140 | + $headers[$normalizedKeys['content-length']] = [$length]; |
|
141 | + } |
|
142 | + } |
|
143 | + } |
|
144 | + } |
|
145 | + } |
|
146 | + return [$stream, $headers]; |
|
147 | + } |
|
148 | + /** |
|
149 | + * Drains the source stream into the "sink" client option. |
|
150 | + * |
|
151 | + * @param string $contentLength Header specifying the amount of |
|
152 | + * data to read. |
|
153 | + * |
|
154 | + * @throws \RuntimeException when the sink option is invalid. |
|
155 | + */ |
|
156 | + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength) : StreamInterface |
|
157 | + { |
|
158 | + // If a content-length header is provided, then stop reading once |
|
159 | + // that number of bytes has been read. This can prevent infinitely |
|
160 | + // reading from a stream when dealing with servers that do not honor |
|
161 | + // Connection: Close headers. |
|
162 | + Psr7\Utils::copyToStream($source, $sink, \strlen($contentLength) > 0 && (int) $contentLength > 0 ? (int) $contentLength : -1); |
|
163 | + $sink->seek(0); |
|
164 | + $source->close(); |
|
165 | + return $sink; |
|
166 | + } |
|
167 | + /** |
|
168 | + * Create a resource and check to ensure it was created successfully |
|
169 | + * |
|
170 | + * @param callable $callback Callable that returns stream resource |
|
171 | + * |
|
172 | + * @return resource |
|
173 | + * |
|
174 | + * @throws \RuntimeException on error |
|
175 | + */ |
|
176 | + private function createResource(callable $callback) |
|
177 | + { |
|
178 | + $errors = []; |
|
179 | + \set_error_handler(static function ($_, $msg, $file, $line) use(&$errors) : bool { |
|
180 | + $errors[] = ['message' => $msg, 'file' => $file, 'line' => $line]; |
|
181 | + return \true; |
|
182 | + }); |
|
183 | + try { |
|
184 | + $resource = $callback(); |
|
185 | + } finally { |
|
186 | + \restore_error_handler(); |
|
187 | + } |
|
188 | + if (!$resource) { |
|
189 | + $message = 'Error creating resource: '; |
|
190 | + foreach ($errors as $err) { |
|
191 | + foreach ($err as $key => $value) { |
|
192 | + $message .= "[{$key}] {$value}" . \PHP_EOL; |
|
193 | + } |
|
194 | + } |
|
195 | + throw new \RuntimeException(\trim($message)); |
|
196 | + } |
|
197 | + return $resource; |
|
198 | + } |
|
199 | + /** |
|
200 | + * @return resource |
|
201 | + */ |
|
202 | + private function createStream(RequestInterface $request, array $options) |
|
203 | + { |
|
204 | + static $methods; |
|
205 | + if (!$methods) { |
|
206 | + $methods = \array_flip(\get_class_methods(__CLASS__)); |
|
207 | + } |
|
208 | + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { |
|
209 | + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); |
|
210 | + } |
|
211 | + // HTTP/1.1 streams using the PHP stream wrapper require a |
|
212 | + // Connection: close header |
|
213 | + if ($request->getProtocolVersion() == '1.1' && !$request->hasHeader('Connection')) { |
|
214 | + $request = $request->withHeader('Connection', 'close'); |
|
215 | + } |
|
216 | + // Ensure SSL is verified by default |
|
217 | + if (!isset($options['verify'])) { |
|
218 | + $options['verify'] = \true; |
|
219 | + } |
|
220 | + $params = []; |
|
221 | + $context = $this->getDefaultContext($request); |
|
222 | + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { |
|
223 | + throw new \InvalidArgumentException('on_headers must be callable'); |
|
224 | + } |
|
225 | + if (!empty($options)) { |
|
226 | + foreach ($options as $key => $value) { |
|
227 | + $method = "add_{$key}"; |
|
228 | + if (isset($methods[$method])) { |
|
229 | + $this->{$method}($request, $context, $value, $params); |
|
230 | + } |
|
231 | + } |
|
232 | + } |
|
233 | + if (isset($options['stream_context'])) { |
|
234 | + if (!\is_array($options['stream_context'])) { |
|
235 | + throw new \InvalidArgumentException('stream_context must be an array'); |
|
236 | + } |
|
237 | + $context = \array_replace_recursive($context, $options['stream_context']); |
|
238 | + } |
|
239 | + // Microsoft NTLM authentication only supported with curl handler |
|
240 | + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { |
|
241 | + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); |
|
242 | + } |
|
243 | + $uri = $this->resolveHost($request, $options); |
|
244 | + $contextResource = $this->createResource(static function () use($context, $params) { |
|
245 | + return \stream_context_create($context, $params); |
|
246 | + }); |
|
247 | + return $this->createResource(function () use($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
248 | + $resource = @\fopen((string) $uri, 'r', \false, $contextResource); |
|
249 | + $this->lastHeaders = $http_response_header ?? []; |
|
250 | + if (\false === $resource) { |
|
251 | + throw new ConnectException(\sprintf('Connection refused for URI %s', $uri), $request, null, $context); |
|
252 | + } |
|
253 | + if (isset($options['read_timeout'])) { |
|
254 | + $readTimeout = $options['read_timeout']; |
|
255 | + $sec = (int) $readTimeout; |
|
256 | + $usec = ($readTimeout - $sec) * 100000; |
|
257 | + \stream_set_timeout($resource, $sec, $usec); |
|
258 | + } |
|
259 | + return $resource; |
|
260 | + }); |
|
261 | + } |
|
262 | + private function resolveHost(RequestInterface $request, array $options) : UriInterface |
|
263 | + { |
|
264 | + $uri = $request->getUri(); |
|
265 | + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { |
|
266 | + if ('v4' === $options['force_ip_resolve']) { |
|
267 | + $records = \dns_get_record($uri->getHost(), \DNS_A); |
|
268 | + if (\false === $records || !isset($records[0]['ip'])) { |
|
269 | + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); |
|
270 | + } |
|
271 | + return $uri->withHost($records[0]['ip']); |
|
272 | + } |
|
273 | + if ('v6' === $options['force_ip_resolve']) { |
|
274 | + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); |
|
275 | + if (\false === $records || !isset($records[0]['ipv6'])) { |
|
276 | + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); |
|
277 | + } |
|
278 | + return $uri->withHost('[' . $records[0]['ipv6'] . ']'); |
|
279 | + } |
|
280 | + } |
|
281 | + return $uri; |
|
282 | + } |
|
283 | + private function getDefaultContext(RequestInterface $request) : array |
|
284 | + { |
|
285 | + $headers = ''; |
|
286 | + foreach ($request->getHeaders() as $name => $value) { |
|
287 | + foreach ($value as $val) { |
|
288 | + $headers .= "{$name}: {$val}\r\n"; |
|
289 | + } |
|
290 | + } |
|
291 | + $context = ['http' => ['method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => \true, 'follow_location' => 0], 'ssl' => ['peer_name' => $request->getUri()->getHost()]]; |
|
292 | + $body = (string) $request->getBody(); |
|
293 | + if ('' !== $body) { |
|
294 | + $context['http']['content'] = $body; |
|
295 | + // Prevent the HTTP handler from adding a Content-Type header. |
|
296 | + if (!$request->hasHeader('Content-Type')) { |
|
297 | + $context['http']['header'] .= "Content-Type:\r\n"; |
|
298 | + } |
|
299 | + } |
|
300 | + $context['http']['header'] = \rtrim($context['http']['header']); |
|
301 | + return $context; |
|
302 | + } |
|
303 | + /** |
|
304 | + * @param mixed $value as passed via Request transfer options. |
|
305 | + */ |
|
306 | + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params) : void |
|
307 | + { |
|
308 | + $uri = null; |
|
309 | + if (!\is_array($value)) { |
|
310 | + $uri = $value; |
|
311 | + } else { |
|
312 | + $scheme = $request->getUri()->getScheme(); |
|
313 | + if (isset($value[$scheme])) { |
|
314 | + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { |
|
315 | + $uri = $value[$scheme]; |
|
316 | + } |
|
317 | + } |
|
318 | + } |
|
319 | + if (!$uri) { |
|
320 | + return; |
|
321 | + } |
|
322 | + $parsed = $this->parse_proxy($uri); |
|
323 | + $options['http']['proxy'] = $parsed['proxy']; |
|
324 | + if ($parsed['auth']) { |
|
325 | + if (!isset($options['http']['header'])) { |
|
326 | + $options['http']['header'] = []; |
|
327 | + } |
|
328 | + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; |
|
329 | + } |
|
330 | + } |
|
331 | + /** |
|
332 | + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. |
|
333 | + */ |
|
334 | + private function parse_proxy(string $url) : array |
|
335 | + { |
|
336 | + $parsed = \parse_url($url); |
|
337 | + if ($parsed !== \false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { |
|
338 | + if (isset($parsed['host']) && isset($parsed['port'])) { |
|
339 | + $auth = null; |
|
340 | + if (isset($parsed['user']) && isset($parsed['pass'])) { |
|
341 | + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); |
|
342 | + } |
|
343 | + return ['proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", 'auth' => $auth ? "Basic {$auth}" : null]; |
|
344 | + } |
|
345 | + } |
|
346 | + // Return proxy as-is. |
|
347 | + return ['proxy' => $url, 'auth' => null]; |
|
348 | + } |
|
349 | + /** |
|
350 | + * @param mixed $value as passed via Request transfer options. |
|
351 | + */ |
|
352 | + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params) : void |
|
353 | + { |
|
354 | + if ($value > 0) { |
|
355 | + $options['http']['timeout'] = $value; |
|
356 | + } |
|
357 | + } |
|
358 | + /** |
|
359 | + * @param mixed $value as passed via Request transfer options. |
|
360 | + */ |
|
361 | + private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params) : void |
|
362 | + { |
|
363 | + if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT || \defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) { |
|
364 | + $options['http']['crypto_method'] = $value; |
|
365 | + return; |
|
366 | + } |
|
367 | + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); |
|
368 | + } |
|
369 | + /** |
|
370 | + * @param mixed $value as passed via Request transfer options. |
|
371 | + */ |
|
372 | + private function add_verify(RequestInterface $request, array &$options, $value, array &$params) : void |
|
373 | + { |
|
374 | + if ($value === \false) { |
|
375 | + $options['ssl']['verify_peer'] = \false; |
|
376 | + $options['ssl']['verify_peer_name'] = \false; |
|
377 | + return; |
|
378 | + } |
|
379 | + if (\is_string($value)) { |
|
380 | + $options['ssl']['cafile'] = $value; |
|
381 | + if (!\file_exists($value)) { |
|
382 | + throw new \RuntimeException("SSL CA bundle not found: {$value}"); |
|
383 | + } |
|
384 | + } elseif ($value !== \true) { |
|
385 | + throw new \InvalidArgumentException('Invalid verify request option'); |
|
386 | + } |
|
387 | + $options['ssl']['verify_peer'] = \true; |
|
388 | + $options['ssl']['verify_peer_name'] = \true; |
|
389 | + $options['ssl']['allow_self_signed'] = \false; |
|
390 | + } |
|
391 | + /** |
|
392 | + * @param mixed $value as passed via Request transfer options. |
|
393 | + */ |
|
394 | + private function add_cert(RequestInterface $request, array &$options, $value, array &$params) : void |
|
395 | + { |
|
396 | + if (\is_array($value)) { |
|
397 | + $options['ssl']['passphrase'] = $value[1]; |
|
398 | + $value = $value[0]; |
|
399 | + } |
|
400 | + if (!\file_exists($value)) { |
|
401 | + throw new \RuntimeException("SSL certificate not found: {$value}"); |
|
402 | + } |
|
403 | + $options['ssl']['local_cert'] = $value; |
|
404 | + } |
|
405 | + /** |
|
406 | + * @param mixed $value as passed via Request transfer options. |
|
407 | + */ |
|
408 | + private function add_progress(RequestInterface $request, array &$options, $value, array &$params) : void |
|
409 | + { |
|
410 | + self::addNotification($params, static function ($code, $a, $b, $c, $transferred, $total) use($value) { |
|
411 | + if ($code == \STREAM_NOTIFY_PROGRESS) { |
|
412 | + // The upload progress cannot be determined. Use 0 for cURL compatibility: |
|
413 | + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
|
414 | + $value($total, $transferred, 0, 0); |
|
415 | + } |
|
416 | + }); |
|
417 | + } |
|
418 | + /** |
|
419 | + * @param mixed $value as passed via Request transfer options. |
|
420 | + */ |
|
421 | + private function add_debug(RequestInterface $request, array &$options, $value, array &$params) : void |
|
422 | + { |
|
423 | + if ($value === \false) { |
|
424 | + return; |
|
425 | + } |
|
426 | + static $map = [\STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', \STREAM_NOTIFY_PROGRESS => 'PROGRESS', \STREAM_NOTIFY_FAILURE => 'FAILURE', \STREAM_NOTIFY_COMPLETED => 'COMPLETED', \STREAM_NOTIFY_RESOLVE => 'RESOLVE']; |
|
427 | + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; |
|
428 | + $value = Utils::debugResource($value); |
|
429 | + $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); |
|
430 | + self::addNotification($params, static function (int $code, ...$passed) use($ident, $value, $map, $args) : void { |
|
431 | + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
|
432 | + foreach (\array_filter($passed) as $i => $v) { |
|
433 | + \fwrite($value, $args[$i] . ': "' . $v . '" '); |
|
434 | + } |
|
435 | + \fwrite($value, "\n"); |
|
436 | + }); |
|
437 | + } |
|
438 | + private static function addNotification(array &$params, callable $notify) : void |
|
439 | + { |
|
440 | + // Wrap the existing function if needed. |
|
441 | + if (!isset($params['notification'])) { |
|
442 | + $params['notification'] = $notify; |
|
443 | + } else { |
|
444 | + $params['notification'] = self::callArray([$params['notification'], $notify]); |
|
445 | + } |
|
446 | + } |
|
447 | + private static function callArray(array $functions) : callable |
|
448 | + { |
|
449 | + return static function (...$args) use($functions) { |
|
450 | + foreach ($functions as $fn) { |
|
451 | + $fn(...$args); |
|
452 | + } |
|
453 | + }; |
|
454 | + } |
|
455 | 455 | } |
@@ -133,7 +133,7 @@ discard block |
||
133 | 133 | // Fix content-length header |
134 | 134 | if (isset($normalizedKeys['content-length'])) { |
135 | 135 | $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
136 | - $length = (int) $stream->getSize(); |
|
136 | + $length = (int)$stream->getSize(); |
|
137 | 137 | if ($length === 0) { |
138 | 138 | unset($headers[$normalizedKeys['content-length']]); |
139 | 139 | } else { |
@@ -159,7 +159,7 @@ discard block |
||
159 | 159 | // that number of bytes has been read. This can prevent infinitely |
160 | 160 | // reading from a stream when dealing with servers that do not honor |
161 | 161 | // Connection: Close headers. |
162 | - Psr7\Utils::copyToStream($source, $sink, \strlen($contentLength) > 0 && (int) $contentLength > 0 ? (int) $contentLength : -1); |
|
162 | + Psr7\Utils::copyToStream($source, $sink, \strlen($contentLength) > 0 && (int)$contentLength > 0 ? (int)$contentLength : -1); |
|
163 | 163 | $sink->seek(0); |
164 | 164 | $source->close(); |
165 | 165 | return $sink; |
@@ -176,7 +176,7 @@ discard block |
||
176 | 176 | private function createResource(callable $callback) |
177 | 177 | { |
178 | 178 | $errors = []; |
179 | - \set_error_handler(static function ($_, $msg, $file, $line) use(&$errors) : bool { |
|
179 | + \set_error_handler(static function($_, $msg, $file, $line) use(&$errors) : bool { |
|
180 | 180 | $errors[] = ['message' => $msg, 'file' => $file, 'line' => $line]; |
181 | 181 | return \true; |
182 | 182 | }); |
@@ -189,7 +189,7 @@ discard block |
||
189 | 189 | $message = 'Error creating resource: '; |
190 | 190 | foreach ($errors as $err) { |
191 | 191 | foreach ($err as $key => $value) { |
192 | - $message .= "[{$key}] {$value}" . \PHP_EOL; |
|
192 | + $message .= "[{$key}] {$value}".\PHP_EOL; |
|
193 | 193 | } |
194 | 194 | } |
195 | 195 | throw new \RuntimeException(\trim($message)); |
@@ -241,18 +241,18 @@ discard block |
||
241 | 241 | throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); |
242 | 242 | } |
243 | 243 | $uri = $this->resolveHost($request, $options); |
244 | - $contextResource = $this->createResource(static function () use($context, $params) { |
|
244 | + $contextResource = $this->createResource(static function() use($context, $params) { |
|
245 | 245 | return \stream_context_create($context, $params); |
246 | 246 | }); |
247 | - return $this->createResource(function () use($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
248 | - $resource = @\fopen((string) $uri, 'r', \false, $contextResource); |
|
247 | + return $this->createResource(function() use($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
248 | + $resource = @\fopen((string)$uri, 'r', \false, $contextResource); |
|
249 | 249 | $this->lastHeaders = $http_response_header ?? []; |
250 | 250 | if (\false === $resource) { |
251 | 251 | throw new ConnectException(\sprintf('Connection refused for URI %s', $uri), $request, null, $context); |
252 | 252 | } |
253 | 253 | if (isset($options['read_timeout'])) { |
254 | 254 | $readTimeout = $options['read_timeout']; |
255 | - $sec = (int) $readTimeout; |
|
255 | + $sec = (int)$readTimeout; |
|
256 | 256 | $usec = ($readTimeout - $sec) * 100000; |
257 | 257 | \stream_set_timeout($resource, $sec, $usec); |
258 | 258 | } |
@@ -275,7 +275,7 @@ discard block |
||
275 | 275 | if (\false === $records || !isset($records[0]['ipv6'])) { |
276 | 276 | throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); |
277 | 277 | } |
278 | - return $uri->withHost('[' . $records[0]['ipv6'] . ']'); |
|
278 | + return $uri->withHost('['.$records[0]['ipv6'].']'); |
|
279 | 279 | } |
280 | 280 | } |
281 | 281 | return $uri; |
@@ -289,7 +289,7 @@ discard block |
||
289 | 289 | } |
290 | 290 | } |
291 | 291 | $context = ['http' => ['method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => \true, 'follow_location' => 0], 'ssl' => ['peer_name' => $request->getUri()->getHost()]]; |
292 | - $body = (string) $request->getBody(); |
|
292 | + $body = (string)$request->getBody(); |
|
293 | 293 | if ('' !== $body) { |
294 | 294 | $context['http']['content'] = $body; |
295 | 295 | // Prevent the HTTP handler from adding a Content-Type header. |
@@ -407,7 +407,7 @@ discard block |
||
407 | 407 | */ |
408 | 408 | private function add_progress(RequestInterface $request, array &$options, $value, array &$params) : void |
409 | 409 | { |
410 | - self::addNotification($params, static function ($code, $a, $b, $c, $transferred, $total) use($value) { |
|
410 | + self::addNotification($params, static function($code, $a, $b, $c, $transferred, $total) use($value) { |
|
411 | 411 | if ($code == \STREAM_NOTIFY_PROGRESS) { |
412 | 412 | // The upload progress cannot be determined. Use 0 for cURL compatibility: |
413 | 413 | // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
@@ -426,11 +426,11 @@ discard block |
||
426 | 426 | static $map = [\STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', \STREAM_NOTIFY_PROGRESS => 'PROGRESS', \STREAM_NOTIFY_FAILURE => 'FAILURE', \STREAM_NOTIFY_COMPLETED => 'COMPLETED', \STREAM_NOTIFY_RESOLVE => 'RESOLVE']; |
427 | 427 | static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; |
428 | 428 | $value = Utils::debugResource($value); |
429 | - $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); |
|
430 | - self::addNotification($params, static function (int $code, ...$passed) use($ident, $value, $map, $args) : void { |
|
429 | + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); |
|
430 | + self::addNotification($params, static function(int $code, ...$passed) use($ident, $value, $map, $args) : void { |
|
431 | 431 | \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
432 | 432 | foreach (\array_filter($passed) as $i => $v) { |
433 | - \fwrite($value, $args[$i] . ': "' . $v . '" '); |
|
433 | + \fwrite($value, $args[$i].': "'.$v.'" '); |
|
434 | 434 | } |
435 | 435 | \fwrite($value, "\n"); |
436 | 436 | }); |
@@ -446,7 +446,7 @@ discard block |
||
446 | 446 | } |
447 | 447 | private static function callArray(array $functions) : callable |
448 | 448 | { |
449 | - return static function (...$args) use($functions) { |
|
449 | + return static function(...$args) use($functions) { |
|
450 | 450 | foreach ($functions as $fn) { |
451 | 451 | $fn(...$args); |
452 | 452 | } |
@@ -17,8 +17,7 @@ |
||
17 | 17 | * |
18 | 18 | * @final |
19 | 19 | */ |
20 | -class CurlMultiHandler |
|
21 | -{ |
|
20 | +class CurlMultiHandler { |
|
22 | 21 | /** |
23 | 22 | * @var CurlFactoryInterface |
24 | 23 | */ |
@@ -18,203 +18,203 @@ |
||
18 | 18 | */ |
19 | 19 | class CurlMultiHandler |
20 | 20 | { |
21 | - /** |
|
22 | - * @var CurlFactoryInterface |
|
23 | - */ |
|
24 | - private $factory; |
|
25 | - /** |
|
26 | - * @var int |
|
27 | - */ |
|
28 | - private $selectTimeout; |
|
29 | - /** |
|
30 | - * @var int Will be higher than 0 when `curl_multi_exec` is still running. |
|
31 | - */ |
|
32 | - private $active = 0; |
|
33 | - /** |
|
34 | - * @var array Request entry handles, indexed by handle id in `addRequest`. |
|
35 | - * |
|
36 | - * @see CurlMultiHandler::addRequest |
|
37 | - */ |
|
38 | - private $handles = []; |
|
39 | - /** |
|
40 | - * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`. |
|
41 | - * |
|
42 | - * @see CurlMultiHandler::addRequest |
|
43 | - */ |
|
44 | - private $delays = []; |
|
45 | - /** |
|
46 | - * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() |
|
47 | - */ |
|
48 | - private $options = []; |
|
49 | - /** @var resource|\CurlMultiHandle */ |
|
50 | - private $_mh; |
|
51 | - /** |
|
52 | - * This handler accepts the following options: |
|
53 | - * |
|
54 | - * - handle_factory: An optional factory used to create curl handles |
|
55 | - * - select_timeout: Optional timeout (in seconds) to block before timing |
|
56 | - * out while selecting curl handles. Defaults to 1 second. |
|
57 | - * - options: An associative array of CURLMOPT_* options and |
|
58 | - * corresponding values for curl_multi_setopt() |
|
59 | - */ |
|
60 | - public function __construct(array $options = []) |
|
61 | - { |
|
62 | - $this->factory = $options['handle_factory'] ?? new CurlFactory(50); |
|
63 | - if (isset($options['select_timeout'])) { |
|
64 | - $this->selectTimeout = $options['select_timeout']; |
|
65 | - } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
|
66 | - @\trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); |
|
67 | - $this->selectTimeout = (int) $selectTimeout; |
|
68 | - } else { |
|
69 | - $this->selectTimeout = 1; |
|
70 | - } |
|
71 | - $this->options = $options['options'] ?? []; |
|
72 | - // unsetting the property forces the first access to go through |
|
73 | - // __get(). |
|
74 | - unset($this->_mh); |
|
75 | - } |
|
76 | - /** |
|
77 | - * @param string $name |
|
78 | - * |
|
79 | - * @return resource|\CurlMultiHandle |
|
80 | - * |
|
81 | - * @throws \BadMethodCallException when another field as `_mh` will be gotten |
|
82 | - * @throws \RuntimeException when curl can not initialize a multi handle |
|
83 | - */ |
|
84 | - public function __get($name) |
|
85 | - { |
|
86 | - if ($name !== '_mh') { |
|
87 | - throw new \BadMethodCallException("Can not get other property as '_mh'."); |
|
88 | - } |
|
89 | - $multiHandle = \curl_multi_init(); |
|
90 | - if (\false === $multiHandle) { |
|
91 | - throw new \RuntimeException('Can not initialize curl multi handle.'); |
|
92 | - } |
|
93 | - $this->_mh = $multiHandle; |
|
94 | - foreach ($this->options as $option => $value) { |
|
95 | - // A warning is raised in case of a wrong option. |
|
96 | - \curl_multi_setopt($this->_mh, $option, $value); |
|
97 | - } |
|
98 | - return $this->_mh; |
|
99 | - } |
|
100 | - public function __destruct() |
|
101 | - { |
|
102 | - if (isset($this->_mh)) { |
|
103 | - \curl_multi_close($this->_mh); |
|
104 | - unset($this->_mh); |
|
105 | - } |
|
106 | - } |
|
107 | - public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
108 | - { |
|
109 | - $easy = $this->factory->create($request, $options); |
|
110 | - $id = (int) $easy->handle; |
|
111 | - $promise = new Promise([$this, 'execute'], function () use($id) { |
|
112 | - return $this->cancel($id); |
|
113 | - }); |
|
114 | - $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
|
115 | - return $promise; |
|
116 | - } |
|
117 | - /** |
|
118 | - * Ticks the curl event loop. |
|
119 | - */ |
|
120 | - public function tick() : void |
|
121 | - { |
|
122 | - // Add any delayed handles if needed. |
|
123 | - if ($this->delays) { |
|
124 | - $currentTime = Utils::currentTime(); |
|
125 | - foreach ($this->delays as $id => $delay) { |
|
126 | - if ($currentTime >= $delay) { |
|
127 | - unset($this->delays[$id]); |
|
128 | - \curl_multi_add_handle($this->_mh, $this->handles[$id]['easy']->handle); |
|
129 | - } |
|
130 | - } |
|
131 | - } |
|
132 | - // Step through the task queue which may add additional requests. |
|
133 | - P\Utils::queue()->run(); |
|
134 | - if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { |
|
135 | - // Perform a usleep if a select returns -1. |
|
136 | - // See: https://bugs.php.net/bug.php?id=61141 |
|
137 | - \usleep(250); |
|
138 | - } |
|
139 | - while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { |
|
140 | - } |
|
141 | - $this->processMessages(); |
|
142 | - } |
|
143 | - /** |
|
144 | - * Runs until all outstanding connections have completed. |
|
145 | - */ |
|
146 | - public function execute() : void |
|
147 | - { |
|
148 | - $queue = P\Utils::queue(); |
|
149 | - while ($this->handles || !$queue->isEmpty()) { |
|
150 | - // If there are no transfers, then sleep for the next delay |
|
151 | - if (!$this->active && $this->delays) { |
|
152 | - \usleep($this->timeToNext()); |
|
153 | - } |
|
154 | - $this->tick(); |
|
155 | - } |
|
156 | - } |
|
157 | - private function addRequest(array $entry) : void |
|
158 | - { |
|
159 | - $easy = $entry['easy']; |
|
160 | - $id = (int) $easy->handle; |
|
161 | - $this->handles[$id] = $entry; |
|
162 | - if (empty($easy->options['delay'])) { |
|
163 | - \curl_multi_add_handle($this->_mh, $easy->handle); |
|
164 | - } else { |
|
165 | - $this->delays[$id] = Utils::currentTime() + $easy->options['delay'] / 1000; |
|
166 | - } |
|
167 | - } |
|
168 | - /** |
|
169 | - * Cancels a handle from sending and removes references to it. |
|
170 | - * |
|
171 | - * @param int $id Handle ID to cancel and remove. |
|
172 | - * |
|
173 | - * @return bool True on success, false on failure. |
|
174 | - */ |
|
175 | - private function cancel($id) : bool |
|
176 | - { |
|
177 | - if (!\is_int($id)) { |
|
178 | - trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); |
|
179 | - } |
|
180 | - // Cannot cancel if it has been processed. |
|
181 | - if (!isset($this->handles[$id])) { |
|
182 | - return \false; |
|
183 | - } |
|
184 | - $handle = $this->handles[$id]['easy']->handle; |
|
185 | - unset($this->delays[$id], $this->handles[$id]); |
|
186 | - \curl_multi_remove_handle($this->_mh, $handle); |
|
187 | - \curl_close($handle); |
|
188 | - return \true; |
|
189 | - } |
|
190 | - private function processMessages() : void |
|
191 | - { |
|
192 | - while ($done = \curl_multi_info_read($this->_mh)) { |
|
193 | - if ($done['msg'] !== \CURLMSG_DONE) { |
|
194 | - // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
|
195 | - continue; |
|
196 | - } |
|
197 | - $id = (int) $done['handle']; |
|
198 | - \curl_multi_remove_handle($this->_mh, $done['handle']); |
|
199 | - if (!isset($this->handles[$id])) { |
|
200 | - // Probably was cancelled. |
|
201 | - continue; |
|
202 | - } |
|
203 | - $entry = $this->handles[$id]; |
|
204 | - unset($this->handles[$id], $this->delays[$id]); |
|
205 | - $entry['easy']->errno = $done['result']; |
|
206 | - $entry['deferred']->resolve(CurlFactory::finish($this, $entry['easy'], $this->factory)); |
|
207 | - } |
|
208 | - } |
|
209 | - private function timeToNext() : int |
|
210 | - { |
|
211 | - $currentTime = Utils::currentTime(); |
|
212 | - $nextTime = \PHP_INT_MAX; |
|
213 | - foreach ($this->delays as $time) { |
|
214 | - if ($time < $nextTime) { |
|
215 | - $nextTime = $time; |
|
216 | - } |
|
217 | - } |
|
218 | - return (int) \max(0, $nextTime - $currentTime) * 1000000; |
|
219 | - } |
|
21 | + /** |
|
22 | + * @var CurlFactoryInterface |
|
23 | + */ |
|
24 | + private $factory; |
|
25 | + /** |
|
26 | + * @var int |
|
27 | + */ |
|
28 | + private $selectTimeout; |
|
29 | + /** |
|
30 | + * @var int Will be higher than 0 when `curl_multi_exec` is still running. |
|
31 | + */ |
|
32 | + private $active = 0; |
|
33 | + /** |
|
34 | + * @var array Request entry handles, indexed by handle id in `addRequest`. |
|
35 | + * |
|
36 | + * @see CurlMultiHandler::addRequest |
|
37 | + */ |
|
38 | + private $handles = []; |
|
39 | + /** |
|
40 | + * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`. |
|
41 | + * |
|
42 | + * @see CurlMultiHandler::addRequest |
|
43 | + */ |
|
44 | + private $delays = []; |
|
45 | + /** |
|
46 | + * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() |
|
47 | + */ |
|
48 | + private $options = []; |
|
49 | + /** @var resource|\CurlMultiHandle */ |
|
50 | + private $_mh; |
|
51 | + /** |
|
52 | + * This handler accepts the following options: |
|
53 | + * |
|
54 | + * - handle_factory: An optional factory used to create curl handles |
|
55 | + * - select_timeout: Optional timeout (in seconds) to block before timing |
|
56 | + * out while selecting curl handles. Defaults to 1 second. |
|
57 | + * - options: An associative array of CURLMOPT_* options and |
|
58 | + * corresponding values for curl_multi_setopt() |
|
59 | + */ |
|
60 | + public function __construct(array $options = []) |
|
61 | + { |
|
62 | + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); |
|
63 | + if (isset($options['select_timeout'])) { |
|
64 | + $this->selectTimeout = $options['select_timeout']; |
|
65 | + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
|
66 | + @\trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); |
|
67 | + $this->selectTimeout = (int) $selectTimeout; |
|
68 | + } else { |
|
69 | + $this->selectTimeout = 1; |
|
70 | + } |
|
71 | + $this->options = $options['options'] ?? []; |
|
72 | + // unsetting the property forces the first access to go through |
|
73 | + // __get(). |
|
74 | + unset($this->_mh); |
|
75 | + } |
|
76 | + /** |
|
77 | + * @param string $name |
|
78 | + * |
|
79 | + * @return resource|\CurlMultiHandle |
|
80 | + * |
|
81 | + * @throws \BadMethodCallException when another field as `_mh` will be gotten |
|
82 | + * @throws \RuntimeException when curl can not initialize a multi handle |
|
83 | + */ |
|
84 | + public function __get($name) |
|
85 | + { |
|
86 | + if ($name !== '_mh') { |
|
87 | + throw new \BadMethodCallException("Can not get other property as '_mh'."); |
|
88 | + } |
|
89 | + $multiHandle = \curl_multi_init(); |
|
90 | + if (\false === $multiHandle) { |
|
91 | + throw new \RuntimeException('Can not initialize curl multi handle.'); |
|
92 | + } |
|
93 | + $this->_mh = $multiHandle; |
|
94 | + foreach ($this->options as $option => $value) { |
|
95 | + // A warning is raised in case of a wrong option. |
|
96 | + \curl_multi_setopt($this->_mh, $option, $value); |
|
97 | + } |
|
98 | + return $this->_mh; |
|
99 | + } |
|
100 | + public function __destruct() |
|
101 | + { |
|
102 | + if (isset($this->_mh)) { |
|
103 | + \curl_multi_close($this->_mh); |
|
104 | + unset($this->_mh); |
|
105 | + } |
|
106 | + } |
|
107 | + public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
108 | + { |
|
109 | + $easy = $this->factory->create($request, $options); |
|
110 | + $id = (int) $easy->handle; |
|
111 | + $promise = new Promise([$this, 'execute'], function () use($id) { |
|
112 | + return $this->cancel($id); |
|
113 | + }); |
|
114 | + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
|
115 | + return $promise; |
|
116 | + } |
|
117 | + /** |
|
118 | + * Ticks the curl event loop. |
|
119 | + */ |
|
120 | + public function tick() : void |
|
121 | + { |
|
122 | + // Add any delayed handles if needed. |
|
123 | + if ($this->delays) { |
|
124 | + $currentTime = Utils::currentTime(); |
|
125 | + foreach ($this->delays as $id => $delay) { |
|
126 | + if ($currentTime >= $delay) { |
|
127 | + unset($this->delays[$id]); |
|
128 | + \curl_multi_add_handle($this->_mh, $this->handles[$id]['easy']->handle); |
|
129 | + } |
|
130 | + } |
|
131 | + } |
|
132 | + // Step through the task queue which may add additional requests. |
|
133 | + P\Utils::queue()->run(); |
|
134 | + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { |
|
135 | + // Perform a usleep if a select returns -1. |
|
136 | + // See: https://bugs.php.net/bug.php?id=61141 |
|
137 | + \usleep(250); |
|
138 | + } |
|
139 | + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { |
|
140 | + } |
|
141 | + $this->processMessages(); |
|
142 | + } |
|
143 | + /** |
|
144 | + * Runs until all outstanding connections have completed. |
|
145 | + */ |
|
146 | + public function execute() : void |
|
147 | + { |
|
148 | + $queue = P\Utils::queue(); |
|
149 | + while ($this->handles || !$queue->isEmpty()) { |
|
150 | + // If there are no transfers, then sleep for the next delay |
|
151 | + if (!$this->active && $this->delays) { |
|
152 | + \usleep($this->timeToNext()); |
|
153 | + } |
|
154 | + $this->tick(); |
|
155 | + } |
|
156 | + } |
|
157 | + private function addRequest(array $entry) : void |
|
158 | + { |
|
159 | + $easy = $entry['easy']; |
|
160 | + $id = (int) $easy->handle; |
|
161 | + $this->handles[$id] = $entry; |
|
162 | + if (empty($easy->options['delay'])) { |
|
163 | + \curl_multi_add_handle($this->_mh, $easy->handle); |
|
164 | + } else { |
|
165 | + $this->delays[$id] = Utils::currentTime() + $easy->options['delay'] / 1000; |
|
166 | + } |
|
167 | + } |
|
168 | + /** |
|
169 | + * Cancels a handle from sending and removes references to it. |
|
170 | + * |
|
171 | + * @param int $id Handle ID to cancel and remove. |
|
172 | + * |
|
173 | + * @return bool True on success, false on failure. |
|
174 | + */ |
|
175 | + private function cancel($id) : bool |
|
176 | + { |
|
177 | + if (!\is_int($id)) { |
|
178 | + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); |
|
179 | + } |
|
180 | + // Cannot cancel if it has been processed. |
|
181 | + if (!isset($this->handles[$id])) { |
|
182 | + return \false; |
|
183 | + } |
|
184 | + $handle = $this->handles[$id]['easy']->handle; |
|
185 | + unset($this->delays[$id], $this->handles[$id]); |
|
186 | + \curl_multi_remove_handle($this->_mh, $handle); |
|
187 | + \curl_close($handle); |
|
188 | + return \true; |
|
189 | + } |
|
190 | + private function processMessages() : void |
|
191 | + { |
|
192 | + while ($done = \curl_multi_info_read($this->_mh)) { |
|
193 | + if ($done['msg'] !== \CURLMSG_DONE) { |
|
194 | + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
|
195 | + continue; |
|
196 | + } |
|
197 | + $id = (int) $done['handle']; |
|
198 | + \curl_multi_remove_handle($this->_mh, $done['handle']); |
|
199 | + if (!isset($this->handles[$id])) { |
|
200 | + // Probably was cancelled. |
|
201 | + continue; |
|
202 | + } |
|
203 | + $entry = $this->handles[$id]; |
|
204 | + unset($this->handles[$id], $this->delays[$id]); |
|
205 | + $entry['easy']->errno = $done['result']; |
|
206 | + $entry['deferred']->resolve(CurlFactory::finish($this, $entry['easy'], $this->factory)); |
|
207 | + } |
|
208 | + } |
|
209 | + private function timeToNext() : int |
|
210 | + { |
|
211 | + $currentTime = Utils::currentTime(); |
|
212 | + $nextTime = \PHP_INT_MAX; |
|
213 | + foreach ($this->delays as $time) { |
|
214 | + if ($time < $nextTime) { |
|
215 | + $nextTime = $time; |
|
216 | + } |
|
217 | + } |
|
218 | + return (int) \max(0, $nextTime - $currentTime) * 1000000; |
|
219 | + } |
|
220 | 220 | } |
@@ -64,7 +64,7 @@ discard block |
||
64 | 64 | $this->selectTimeout = $options['select_timeout']; |
65 | 65 | } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
66 | 66 | @\trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); |
67 | - $this->selectTimeout = (int) $selectTimeout; |
|
67 | + $this->selectTimeout = (int)$selectTimeout; |
|
68 | 68 | } else { |
69 | 69 | $this->selectTimeout = 1; |
70 | 70 | } |
@@ -107,8 +107,8 @@ discard block |
||
107 | 107 | public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
108 | 108 | { |
109 | 109 | $easy = $this->factory->create($request, $options); |
110 | - $id = (int) $easy->handle; |
|
111 | - $promise = new Promise([$this, 'execute'], function () use($id) { |
|
110 | + $id = (int)$easy->handle; |
|
111 | + $promise = new Promise([$this, 'execute'], function() use($id) { |
|
112 | 112 | return $this->cancel($id); |
113 | 113 | }); |
114 | 114 | $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
@@ -157,7 +157,7 @@ discard block |
||
157 | 157 | private function addRequest(array $entry) : void |
158 | 158 | { |
159 | 159 | $easy = $entry['easy']; |
160 | - $id = (int) $easy->handle; |
|
160 | + $id = (int)$easy->handle; |
|
161 | 161 | $this->handles[$id] = $entry; |
162 | 162 | if (empty($easy->options['delay'])) { |
163 | 163 | \curl_multi_add_handle($this->_mh, $easy->handle); |
@@ -194,7 +194,7 @@ discard block |
||
194 | 194 | // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
195 | 195 | continue; |
196 | 196 | } |
197 | - $id = (int) $done['handle']; |
|
197 | + $id = (int)$done['handle']; |
|
198 | 198 | \curl_multi_remove_handle($this->_mh, $done['handle']); |
199 | 199 | if (!isset($this->handles[$id])) { |
200 | 200 | // Probably was cancelled. |
@@ -215,6 +215,6 @@ discard block |
||
215 | 215 | $nextTime = $time; |
216 | 216 | } |
217 | 217 | } |
218 | - return (int) \max(0, $nextTime - $currentTime) * 1000000; |
|
218 | + return (int)\max(0, $nextTime - $currentTime) * 1000000; |
|
219 | 219 | } |
220 | 220 | } |
@@ -7,8 +7,7 @@ |
||
7 | 7 | /** |
8 | 8 | * @internal |
9 | 9 | */ |
10 | -final class HeaderProcessor |
|
11 | -{ |
|
10 | +final class HeaderProcessor { |
|
12 | 11 | /** |
13 | 12 | * Returns the HTTP version, status code, reason phrase, and headers. |
14 | 13 | * |
@@ -8,29 +8,29 @@ |
||
8 | 8 | */ |
9 | 9 | final class HeaderProcessor |
10 | 10 | { |
11 | - /** |
|
12 | - * Returns the HTTP version, status code, reason phrase, and headers. |
|
13 | - * |
|
14 | - * @param string[] $headers |
|
15 | - * |
|
16 | - * @return array{0:string, 1:int, 2:?string, 3:array} |
|
17 | - * |
|
18 | - * @throws \RuntimeException |
|
19 | - */ |
|
20 | - public static function parseHeaders(array $headers) : array |
|
21 | - { |
|
22 | - if ($headers === []) { |
|
23 | - throw new \RuntimeException('Expected a non-empty array of header data'); |
|
24 | - } |
|
25 | - $parts = \explode(' ', \array_shift($headers), 3); |
|
26 | - $version = \explode('/', $parts[0])[1] ?? null; |
|
27 | - if ($version === null) { |
|
28 | - throw new \RuntimeException('HTTP version missing from header data'); |
|
29 | - } |
|
30 | - $status = $parts[1] ?? null; |
|
31 | - if ($status === null) { |
|
32 | - throw new \RuntimeException('HTTP status code missing from header data'); |
|
33 | - } |
|
34 | - return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
35 | - } |
|
11 | + /** |
|
12 | + * Returns the HTTP version, status code, reason phrase, and headers. |
|
13 | + * |
|
14 | + * @param string[] $headers |
|
15 | + * |
|
16 | + * @return array{0:string, 1:int, 2:?string, 3:array} |
|
17 | + * |
|
18 | + * @throws \RuntimeException |
|
19 | + */ |
|
20 | + public static function parseHeaders(array $headers) : array |
|
21 | + { |
|
22 | + if ($headers === []) { |
|
23 | + throw new \RuntimeException('Expected a non-empty array of header data'); |
|
24 | + } |
|
25 | + $parts = \explode(' ', \array_shift($headers), 3); |
|
26 | + $version = \explode('/', $parts[0])[1] ?? null; |
|
27 | + if ($version === null) { |
|
28 | + throw new \RuntimeException('HTTP version missing from header data'); |
|
29 | + } |
|
30 | + $status = $parts[1] ?? null; |
|
31 | + if ($status === null) { |
|
32 | + throw new \RuntimeException('HTTP status code missing from header data'); |
|
33 | + } |
|
34 | + return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
35 | + } |
|
36 | 36 | } |
@@ -31,6 +31,6 @@ |
||
31 | 31 | if ($status === null) { |
32 | 32 | throw new \RuntimeException('HTTP status code missing from header data'); |
33 | 33 | } |
34 | - return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
34 | + return [$version, (int)$status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
35 | 35 | } |
36 | 36 | } |
@@ -13,8 +13,7 @@ |
||
13 | 13 | * |
14 | 14 | * @internal |
15 | 15 | */ |
16 | -final class EasyHandle |
|
17 | -{ |
|
16 | +final class EasyHandle { |
|
18 | 17 | /** |
19 | 18 | * @var resource|\CurlHandle cURL resource |
20 | 19 | */ |
@@ -14,78 +14,78 @@ |
||
14 | 14 | */ |
15 | 15 | final class EasyHandle |
16 | 16 | { |
17 | - /** |
|
18 | - * @var resource|\CurlHandle cURL resource |
|
19 | - */ |
|
20 | - public $handle; |
|
21 | - /** |
|
22 | - * @var StreamInterface Where data is being written |
|
23 | - */ |
|
24 | - public $sink; |
|
25 | - /** |
|
26 | - * @var array Received HTTP headers so far |
|
27 | - */ |
|
28 | - public $headers = []; |
|
29 | - /** |
|
30 | - * @var ResponseInterface|null Received response (if any) |
|
31 | - */ |
|
32 | - public $response; |
|
33 | - /** |
|
34 | - * @var RequestInterface Request being sent |
|
35 | - */ |
|
36 | - public $request; |
|
37 | - /** |
|
38 | - * @var array Request options |
|
39 | - */ |
|
40 | - public $options = []; |
|
41 | - /** |
|
42 | - * @var int cURL error number (if any) |
|
43 | - */ |
|
44 | - public $errno = 0; |
|
45 | - /** |
|
46 | - * @var \Throwable|null Exception during on_headers (if any) |
|
47 | - */ |
|
48 | - public $onHeadersException; |
|
49 | - /** |
|
50 | - * @var \Exception|null Exception during createResponse (if any) |
|
51 | - */ |
|
52 | - public $createResponseException; |
|
53 | - /** |
|
54 | - * Attach a response to the easy handle based on the received headers. |
|
55 | - * |
|
56 | - * @throws \RuntimeException if no headers have been received or the first |
|
57 | - * header line is invalid. |
|
58 | - */ |
|
59 | - public function createResponse() : void |
|
60 | - { |
|
61 | - [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers); |
|
62 | - $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
63 | - if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { |
|
64 | - $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
65 | - unset($headers[$normalizedKeys['content-encoding']]); |
|
66 | - if (isset($normalizedKeys['content-length'])) { |
|
67 | - $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
68 | - $bodyLength = (int) $this->sink->getSize(); |
|
69 | - if ($bodyLength) { |
|
70 | - $headers[$normalizedKeys['content-length']] = $bodyLength; |
|
71 | - } else { |
|
72 | - unset($headers[$normalizedKeys['content-length']]); |
|
73 | - } |
|
74 | - } |
|
75 | - } |
|
76 | - // Attach a response to the easy handle with the parsed headers. |
|
77 | - $this->response = new Response($status, $headers, $this->sink, $ver, $reason); |
|
78 | - } |
|
79 | - /** |
|
80 | - * @param string $name |
|
81 | - * |
|
82 | - * @return void |
|
83 | - * |
|
84 | - * @throws \BadMethodCallException |
|
85 | - */ |
|
86 | - public function __get($name) |
|
87 | - { |
|
88 | - $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; |
|
89 | - throw new \BadMethodCallException($msg); |
|
90 | - } |
|
17 | + /** |
|
18 | + * @var resource|\CurlHandle cURL resource |
|
19 | + */ |
|
20 | + public $handle; |
|
21 | + /** |
|
22 | + * @var StreamInterface Where data is being written |
|
23 | + */ |
|
24 | + public $sink; |
|
25 | + /** |
|
26 | + * @var array Received HTTP headers so far |
|
27 | + */ |
|
28 | + public $headers = []; |
|
29 | + /** |
|
30 | + * @var ResponseInterface|null Received response (if any) |
|
31 | + */ |
|
32 | + public $response; |
|
33 | + /** |
|
34 | + * @var RequestInterface Request being sent |
|
35 | + */ |
|
36 | + public $request; |
|
37 | + /** |
|
38 | + * @var array Request options |
|
39 | + */ |
|
40 | + public $options = []; |
|
41 | + /** |
|
42 | + * @var int cURL error number (if any) |
|
43 | + */ |
|
44 | + public $errno = 0; |
|
45 | + /** |
|
46 | + * @var \Throwable|null Exception during on_headers (if any) |
|
47 | + */ |
|
48 | + public $onHeadersException; |
|
49 | + /** |
|
50 | + * @var \Exception|null Exception during createResponse (if any) |
|
51 | + */ |
|
52 | + public $createResponseException; |
|
53 | + /** |
|
54 | + * Attach a response to the easy handle based on the received headers. |
|
55 | + * |
|
56 | + * @throws \RuntimeException if no headers have been received or the first |
|
57 | + * header line is invalid. |
|
58 | + */ |
|
59 | + public function createResponse() : void |
|
60 | + { |
|
61 | + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers); |
|
62 | + $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
63 | + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { |
|
64 | + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
65 | + unset($headers[$normalizedKeys['content-encoding']]); |
|
66 | + if (isset($normalizedKeys['content-length'])) { |
|
67 | + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
68 | + $bodyLength = (int) $this->sink->getSize(); |
|
69 | + if ($bodyLength) { |
|
70 | + $headers[$normalizedKeys['content-length']] = $bodyLength; |
|
71 | + } else { |
|
72 | + unset($headers[$normalizedKeys['content-length']]); |
|
73 | + } |
|
74 | + } |
|
75 | + } |
|
76 | + // Attach a response to the easy handle with the parsed headers. |
|
77 | + $this->response = new Response($status, $headers, $this->sink, $ver, $reason); |
|
78 | + } |
|
79 | + /** |
|
80 | + * @param string $name |
|
81 | + * |
|
82 | + * @return void |
|
83 | + * |
|
84 | + * @throws \BadMethodCallException |
|
85 | + */ |
|
86 | + public function __get($name) |
|
87 | + { |
|
88 | + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; |
|
89 | + throw new \BadMethodCallException($msg); |
|
90 | + } |
|
91 | 91 | } |
@@ -65,7 +65,7 @@ discard block |
||
65 | 65 | unset($headers[$normalizedKeys['content-encoding']]); |
66 | 66 | if (isset($normalizedKeys['content-length'])) { |
67 | 67 | $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
68 | - $bodyLength = (int) $this->sink->getSize(); |
|
68 | + $bodyLength = (int)$this->sink->getSize(); |
|
69 | 69 | if ($bodyLength) { |
70 | 70 | $headers[$normalizedKeys['content-length']] = $bodyLength; |
71 | 71 | } else { |
@@ -85,7 +85,7 @@ discard block |
||
85 | 85 | */ |
86 | 86 | public function __get($name) |
87 | 87 | { |
88 | - $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; |
|
88 | + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name; |
|
89 | 89 | throw new \BadMethodCallException($msg); |
90 | 90 | } |
91 | 91 | } |
@@ -11,8 +11,7 @@ |
||
11 | 11 | * |
12 | 12 | * @final |
13 | 13 | */ |
14 | -class Proxy |
|
15 | -{ |
|
14 | +class Proxy { |
|
16 | 15 | /** |
17 | 16 | * Sends synchronous requests to a specific handler while sending all other |
18 | 17 | * requests to another handler. |
@@ -12,38 +12,38 @@ |
||
12 | 12 | */ |
13 | 13 | class Proxy |
14 | 14 | { |
15 | - /** |
|
16 | - * Sends synchronous requests to a specific handler while sending all other |
|
17 | - * requests to another handler. |
|
18 | - * |
|
19 | - * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $default Handler used for normal responses |
|
20 | - * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $sync Handler used for synchronous responses. |
|
21 | - * |
|
22 | - * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the composed handler. |
|
23 | - */ |
|
24 | - public static function wrapSync(callable $default, callable $sync) : callable |
|
25 | - { |
|
26 | - return static function (RequestInterface $request, array $options) use($default, $sync) : PromiseInterface { |
|
27 | - return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); |
|
28 | - }; |
|
29 | - } |
|
30 | - /** |
|
31 | - * Sends streaming requests to a streaming compatible handler while sending |
|
32 | - * all other requests to a default handler. |
|
33 | - * |
|
34 | - * This, for example, could be useful for taking advantage of the |
|
35 | - * performance benefits of curl while still supporting true streaming |
|
36 | - * through the StreamHandler. |
|
37 | - * |
|
38 | - * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $default Handler used for non-streaming responses |
|
39 | - * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $streaming Handler used for streaming responses |
|
40 | - * |
|
41 | - * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the composed handler. |
|
42 | - */ |
|
43 | - public static function wrapStreaming(callable $default, callable $streaming) : callable |
|
44 | - { |
|
45 | - return static function (RequestInterface $request, array $options) use($default, $streaming) : PromiseInterface { |
|
46 | - return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); |
|
47 | - }; |
|
48 | - } |
|
15 | + /** |
|
16 | + * Sends synchronous requests to a specific handler while sending all other |
|
17 | + * requests to another handler. |
|
18 | + * |
|
19 | + * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $default Handler used for normal responses |
|
20 | + * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $sync Handler used for synchronous responses. |
|
21 | + * |
|
22 | + * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the composed handler. |
|
23 | + */ |
|
24 | + public static function wrapSync(callable $default, callable $sync) : callable |
|
25 | + { |
|
26 | + return static function (RequestInterface $request, array $options) use($default, $sync) : PromiseInterface { |
|
27 | + return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); |
|
28 | + }; |
|
29 | + } |
|
30 | + /** |
|
31 | + * Sends streaming requests to a streaming compatible handler while sending |
|
32 | + * all other requests to a default handler. |
|
33 | + * |
|
34 | + * This, for example, could be useful for taking advantage of the |
|
35 | + * performance benefits of curl while still supporting true streaming |
|
36 | + * through the StreamHandler. |
|
37 | + * |
|
38 | + * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $default Handler used for non-streaming responses |
|
39 | + * @param callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface $streaming Handler used for streaming responses |
|
40 | + * |
|
41 | + * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the composed handler. |
|
42 | + */ |
|
43 | + public static function wrapStreaming(callable $default, callable $streaming) : callable |
|
44 | + { |
|
45 | + return static function (RequestInterface $request, array $options) use($default, $streaming) : PromiseInterface { |
|
46 | + return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); |
|
47 | + }; |
|
48 | + } |
|
49 | 49 | } |
@@ -23,7 +23,7 @@ discard block |
||
23 | 23 | */ |
24 | 24 | public static function wrapSync(callable $default, callable $sync) : callable |
25 | 25 | { |
26 | - return static function (RequestInterface $request, array $options) use($default, $sync) : PromiseInterface { |
|
26 | + return static function(RequestInterface $request, array $options) use($default, $sync) : PromiseInterface { |
|
27 | 27 | return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options); |
28 | 28 | }; |
29 | 29 | } |
@@ -42,7 +42,7 @@ discard block |
||
42 | 42 | */ |
43 | 43 | public static function wrapStreaming(callable $default, callable $streaming) : callable |
44 | 44 | { |
45 | - return static function (RequestInterface $request, array $options) use($default, $streaming) : PromiseInterface { |
|
45 | + return static function(RequestInterface $request, array $options) use($default, $streaming) : PromiseInterface { |
|
46 | 46 | return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options); |
47 | 47 | }; |
48 | 48 | } |
@@ -14,8 +14,7 @@ |
||
14 | 14 | * |
15 | 15 | * @final |
16 | 16 | */ |
17 | -class CurlHandler |
|
18 | -{ |
|
17 | +class CurlHandler { |
|
19 | 18 | /** |
20 | 19 | * @var CurlFactoryInterface |
21 | 20 | */ |
@@ -15,29 +15,29 @@ |
||
15 | 15 | */ |
16 | 16 | class CurlHandler |
17 | 17 | { |
18 | - /** |
|
19 | - * @var CurlFactoryInterface |
|
20 | - */ |
|
21 | - private $factory; |
|
22 | - /** |
|
23 | - * Accepts an associative array of options: |
|
24 | - * |
|
25 | - * - handle_factory: Optional curl factory used to create cURL handles. |
|
26 | - * |
|
27 | - * @param array{handle_factory?: ?CurlFactoryInterface} $options Array of options to use with the handler |
|
28 | - */ |
|
29 | - public function __construct(array $options = []) |
|
30 | - { |
|
31 | - $this->factory = $options['handle_factory'] ?? new CurlFactory(3); |
|
32 | - } |
|
33 | - public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
34 | - { |
|
35 | - if (isset($options['delay'])) { |
|
36 | - \usleep($options['delay'] * 1000); |
|
37 | - } |
|
38 | - $easy = $this->factory->create($request, $options); |
|
39 | - \curl_exec($easy->handle); |
|
40 | - $easy->errno = \curl_errno($easy->handle); |
|
41 | - return CurlFactory::finish($this, $easy, $this->factory); |
|
42 | - } |
|
18 | + /** |
|
19 | + * @var CurlFactoryInterface |
|
20 | + */ |
|
21 | + private $factory; |
|
22 | + /** |
|
23 | + * Accepts an associative array of options: |
|
24 | + * |
|
25 | + * - handle_factory: Optional curl factory used to create cURL handles. |
|
26 | + * |
|
27 | + * @param array{handle_factory?: ?CurlFactoryInterface} $options Array of options to use with the handler |
|
28 | + */ |
|
29 | + public function __construct(array $options = []) |
|
30 | + { |
|
31 | + $this->factory = $options['handle_factory'] ?? new CurlFactory(3); |
|
32 | + } |
|
33 | + public function __invoke(RequestInterface $request, array $options) : PromiseInterface |
|
34 | + { |
|
35 | + if (isset($options['delay'])) { |
|
36 | + \usleep($options['delay'] * 1000); |
|
37 | + } |
|
38 | + $easy = $this->factory->create($request, $options); |
|
39 | + \curl_exec($easy->handle); |
|
40 | + $easy->errno = \curl_errno($easy->handle); |
|
41 | + return CurlFactory::finish($this, $easy, $this->factory); |
|
42 | + } |
|
43 | 43 | } |