@@ -19,210 +19,210 @@ |
||
| 19 | 19 | */ |
| 20 | 20 | class RedirectMiddleware |
| 21 | 21 | { |
| 22 | - public const HISTORY_HEADER = 'X-Guzzle-Redirect-History'; |
|
| 23 | - |
|
| 24 | - public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History'; |
|
| 25 | - |
|
| 26 | - /** |
|
| 27 | - * @var array |
|
| 28 | - */ |
|
| 29 | - public static $defaultSettings = [ |
|
| 30 | - 'max' => 5, |
|
| 31 | - 'protocols' => ['http', 'https'], |
|
| 32 | - 'strict' => false, |
|
| 33 | - 'referer' => false, |
|
| 34 | - 'track_redirects' => false, |
|
| 35 | - ]; |
|
| 36 | - |
|
| 37 | - /** |
|
| 38 | - * @var callable(RequestInterface, array): PromiseInterface |
|
| 39 | - */ |
|
| 40 | - private $nextHandler; |
|
| 41 | - |
|
| 42 | - /** |
|
| 43 | - * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
| 44 | - */ |
|
| 45 | - public function __construct(callable $nextHandler) |
|
| 46 | - { |
|
| 47 | - $this->nextHandler = $nextHandler; |
|
| 48 | - } |
|
| 49 | - |
|
| 50 | - public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 51 | - { |
|
| 52 | - $fn = $this->nextHandler; |
|
| 53 | - |
|
| 54 | - if (empty($options['allow_redirects'])) { |
|
| 55 | - return $fn($request, $options); |
|
| 56 | - } |
|
| 57 | - |
|
| 58 | - if ($options['allow_redirects'] === true) { |
|
| 59 | - $options['allow_redirects'] = self::$defaultSettings; |
|
| 60 | - } elseif (!\is_array($options['allow_redirects'])) { |
|
| 61 | - throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); |
|
| 62 | - } else { |
|
| 63 | - // Merge the default settings with the provided settings |
|
| 64 | - $options['allow_redirects'] += self::$defaultSettings; |
|
| 65 | - } |
|
| 66 | - |
|
| 67 | - if (empty($options['allow_redirects']['max'])) { |
|
| 68 | - return $fn($request, $options); |
|
| 69 | - } |
|
| 70 | - |
|
| 71 | - return $fn($request, $options) |
|
| 72 | - ->then(function (ResponseInterface $response) use ($request, $options) { |
|
| 73 | - return $this->checkRedirect($request, $options, $response); |
|
| 74 | - }); |
|
| 75 | - } |
|
| 76 | - |
|
| 77 | - /** |
|
| 78 | - * @return ResponseInterface|PromiseInterface |
|
| 79 | - */ |
|
| 80 | - public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) |
|
| 81 | - { |
|
| 82 | - if (\strpos((string) $response->getStatusCode(), '3') !== 0 |
|
| 83 | - || !$response->hasHeader('Location') |
|
| 84 | - ) { |
|
| 85 | - return $response; |
|
| 86 | - } |
|
| 87 | - |
|
| 88 | - $this->guardMax($request, $response, $options); |
|
| 89 | - $nextRequest = $this->modifyRequest($request, $options, $response); |
|
| 90 | - |
|
| 91 | - // If authorization is handled by curl, unset it if URI is cross-origin. |
|
| 92 | - if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { |
|
| 93 | - unset( |
|
| 94 | - $options['curl'][\CURLOPT_HTTPAUTH], |
|
| 95 | - $options['curl'][\CURLOPT_USERPWD] |
|
| 96 | - ); |
|
| 97 | - } |
|
| 98 | - |
|
| 99 | - if (isset($options['allow_redirects']['on_redirect'])) { |
|
| 100 | - ($options['allow_redirects']['on_redirect'])( |
|
| 101 | - $request, |
|
| 102 | - $response, |
|
| 103 | - $nextRequest->getUri() |
|
| 104 | - ); |
|
| 105 | - } |
|
| 106 | - |
|
| 107 | - $promise = $this($nextRequest, $options); |
|
| 108 | - |
|
| 109 | - // Add headers to be able to track history of redirects. |
|
| 110 | - if (!empty($options['allow_redirects']['track_redirects'])) { |
|
| 111 | - return $this->withTracking( |
|
| 112 | - $promise, |
|
| 113 | - (string) $nextRequest->getUri(), |
|
| 114 | - $response->getStatusCode() |
|
| 115 | - ); |
|
| 116 | - } |
|
| 117 | - |
|
| 118 | - return $promise; |
|
| 119 | - } |
|
| 120 | - |
|
| 121 | - /** |
|
| 122 | - * Enable tracking on promise. |
|
| 123 | - */ |
|
| 124 | - private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface |
|
| 125 | - { |
|
| 126 | - return $promise->then( |
|
| 127 | - static function (ResponseInterface $response) use ($uri, $statusCode) { |
|
| 128 | - // Note that we are pushing to the front of the list as this |
|
| 129 | - // would be an earlier response than what is currently present |
|
| 130 | - // in the history header. |
|
| 131 | - $historyHeader = $response->getHeader(self::HISTORY_HEADER); |
|
| 132 | - $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); |
|
| 133 | - \array_unshift($historyHeader, $uri); |
|
| 134 | - \array_unshift($statusHeader, (string) $statusCode); |
|
| 135 | - |
|
| 136 | - return $response->withHeader(self::HISTORY_HEADER, $historyHeader) |
|
| 137 | - ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); |
|
| 138 | - } |
|
| 139 | - ); |
|
| 140 | - } |
|
| 141 | - |
|
| 142 | - /** |
|
| 143 | - * Check for too many redirects. |
|
| 144 | - * |
|
| 145 | - * @throws TooManyRedirectsException Too many redirects. |
|
| 146 | - */ |
|
| 147 | - private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void |
|
| 148 | - { |
|
| 149 | - $current = $options['__redirect_count'] |
|
| 150 | - ?? 0; |
|
| 151 | - $options['__redirect_count'] = $current + 1; |
|
| 152 | - $max = $options['allow_redirects']['max']; |
|
| 153 | - |
|
| 154 | - if ($options['__redirect_count'] > $max) { |
|
| 155 | - throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); |
|
| 156 | - } |
|
| 157 | - } |
|
| 158 | - |
|
| 159 | - public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface |
|
| 160 | - { |
|
| 161 | - // Request modifications to apply. |
|
| 162 | - $modify = []; |
|
| 163 | - $protocols = $options['allow_redirects']['protocols']; |
|
| 164 | - |
|
| 165 | - // Use a GET request if this is an entity enclosing request and we are |
|
| 166 | - // not forcing RFC compliance, but rather emulating what all browsers |
|
| 167 | - // would do. |
|
| 168 | - $statusCode = $response->getStatusCode(); |
|
| 169 | - if ($statusCode == 303 |
|
| 170 | - || ($statusCode <= 302 && !$options['allow_redirects']['strict']) |
|
| 171 | - ) { |
|
| 172 | - $safeMethods = ['GET', 'HEAD', 'OPTIONS']; |
|
| 173 | - $requestMethod = $request->getMethod(); |
|
| 174 | - |
|
| 175 | - $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; |
|
| 176 | - $modify['body'] = ''; |
|
| 177 | - } |
|
| 178 | - |
|
| 179 | - $uri = self::redirectUri($request, $response, $protocols); |
|
| 180 | - if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { |
|
| 181 | - $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; |
|
| 182 | - $uri = Utils::idnUriConvert($uri, $idnOptions); |
|
| 183 | - } |
|
| 184 | - |
|
| 185 | - $modify['uri'] = $uri; |
|
| 186 | - Psr7\Message::rewindBody($request); |
|
| 187 | - |
|
| 188 | - // Add the Referer header if it is told to do so and only |
|
| 189 | - // add the header if we are not redirecting from https to http. |
|
| 190 | - if ($options['allow_redirects']['referer'] |
|
| 191 | - && $modify['uri']->getScheme() === $request->getUri()->getScheme() |
|
| 192 | - ) { |
|
| 193 | - $uri = $request->getUri()->withUserInfo(''); |
|
| 194 | - $modify['set_headers']['Referer'] = (string) $uri; |
|
| 195 | - } else { |
|
| 196 | - $modify['remove_headers'][] = 'Referer'; |
|
| 197 | - } |
|
| 198 | - |
|
| 199 | - // Remove Authorization and Cookie headers if URI is cross-origin. |
|
| 200 | - if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { |
|
| 201 | - $modify['remove_headers'][] = 'Authorization'; |
|
| 202 | - $modify['remove_headers'][] = 'Cookie'; |
|
| 203 | - } |
|
| 204 | - |
|
| 205 | - return Psr7\Utils::modifyRequest($request, $modify); |
|
| 206 | - } |
|
| 207 | - |
|
| 208 | - /** |
|
| 209 | - * Set the appropriate URL on the request based on the location header. |
|
| 210 | - */ |
|
| 211 | - private static function redirectUri( |
|
| 212 | - RequestInterface $request, |
|
| 213 | - ResponseInterface $response, |
|
| 214 | - array $protocols |
|
| 215 | - ): UriInterface { |
|
| 216 | - $location = Psr7\UriResolver::resolve( |
|
| 217 | - $request->getUri(), |
|
| 218 | - new Psr7\Uri($response->getHeaderLine('Location')) |
|
| 219 | - ); |
|
| 220 | - |
|
| 221 | - // Ensure that the redirect URI is allowed based on the protocols. |
|
| 222 | - if (!\in_array($location->getScheme(), $protocols)) { |
|
| 223 | - throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); |
|
| 224 | - } |
|
| 225 | - |
|
| 226 | - return $location; |
|
| 227 | - } |
|
| 22 | + public const HISTORY_HEADER = 'X-Guzzle-Redirect-History'; |
|
| 23 | + |
|
| 24 | + public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History'; |
|
| 25 | + |
|
| 26 | + /** |
|
| 27 | + * @var array |
|
| 28 | + */ |
|
| 29 | + public static $defaultSettings = [ |
|
| 30 | + 'max' => 5, |
|
| 31 | + 'protocols' => ['http', 'https'], |
|
| 32 | + 'strict' => false, |
|
| 33 | + 'referer' => false, |
|
| 34 | + 'track_redirects' => false, |
|
| 35 | + ]; |
|
| 36 | + |
|
| 37 | + /** |
|
| 38 | + * @var callable(RequestInterface, array): PromiseInterface |
|
| 39 | + */ |
|
| 40 | + private $nextHandler; |
|
| 41 | + |
|
| 42 | + /** |
|
| 43 | + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
| 44 | + */ |
|
| 45 | + public function __construct(callable $nextHandler) |
|
| 46 | + { |
|
| 47 | + $this->nextHandler = $nextHandler; |
|
| 48 | + } |
|
| 49 | + |
|
| 50 | + public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 51 | + { |
|
| 52 | + $fn = $this->nextHandler; |
|
| 53 | + |
|
| 54 | + if (empty($options['allow_redirects'])) { |
|
| 55 | + return $fn($request, $options); |
|
| 56 | + } |
|
| 57 | + |
|
| 58 | + if ($options['allow_redirects'] === true) { |
|
| 59 | + $options['allow_redirects'] = self::$defaultSettings; |
|
| 60 | + } elseif (!\is_array($options['allow_redirects'])) { |
|
| 61 | + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); |
|
| 62 | + } else { |
|
| 63 | + // Merge the default settings with the provided settings |
|
| 64 | + $options['allow_redirects'] += self::$defaultSettings; |
|
| 65 | + } |
|
| 66 | + |
|
| 67 | + if (empty($options['allow_redirects']['max'])) { |
|
| 68 | + return $fn($request, $options); |
|
| 69 | + } |
|
| 70 | + |
|
| 71 | + return $fn($request, $options) |
|
| 72 | + ->then(function (ResponseInterface $response) use ($request, $options) { |
|
| 73 | + return $this->checkRedirect($request, $options, $response); |
|
| 74 | + }); |
|
| 75 | + } |
|
| 76 | + |
|
| 77 | + /** |
|
| 78 | + * @return ResponseInterface|PromiseInterface |
|
| 79 | + */ |
|
| 80 | + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) |
|
| 81 | + { |
|
| 82 | + if (\strpos((string) $response->getStatusCode(), '3') !== 0 |
|
| 83 | + || !$response->hasHeader('Location') |
|
| 84 | + ) { |
|
| 85 | + return $response; |
|
| 86 | + } |
|
| 87 | + |
|
| 88 | + $this->guardMax($request, $response, $options); |
|
| 89 | + $nextRequest = $this->modifyRequest($request, $options, $response); |
|
| 90 | + |
|
| 91 | + // If authorization is handled by curl, unset it if URI is cross-origin. |
|
| 92 | + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { |
|
| 93 | + unset( |
|
| 94 | + $options['curl'][\CURLOPT_HTTPAUTH], |
|
| 95 | + $options['curl'][\CURLOPT_USERPWD] |
|
| 96 | + ); |
|
| 97 | + } |
|
| 98 | + |
|
| 99 | + if (isset($options['allow_redirects']['on_redirect'])) { |
|
| 100 | + ($options['allow_redirects']['on_redirect'])( |
|
| 101 | + $request, |
|
| 102 | + $response, |
|
| 103 | + $nextRequest->getUri() |
|
| 104 | + ); |
|
| 105 | + } |
|
| 106 | + |
|
| 107 | + $promise = $this($nextRequest, $options); |
|
| 108 | + |
|
| 109 | + // Add headers to be able to track history of redirects. |
|
| 110 | + if (!empty($options['allow_redirects']['track_redirects'])) { |
|
| 111 | + return $this->withTracking( |
|
| 112 | + $promise, |
|
| 113 | + (string) $nextRequest->getUri(), |
|
| 114 | + $response->getStatusCode() |
|
| 115 | + ); |
|
| 116 | + } |
|
| 117 | + |
|
| 118 | + return $promise; |
|
| 119 | + } |
|
| 120 | + |
|
| 121 | + /** |
|
| 122 | + * Enable tracking on promise. |
|
| 123 | + */ |
|
| 124 | + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface |
|
| 125 | + { |
|
| 126 | + return $promise->then( |
|
| 127 | + static function (ResponseInterface $response) use ($uri, $statusCode) { |
|
| 128 | + // Note that we are pushing to the front of the list as this |
|
| 129 | + // would be an earlier response than what is currently present |
|
| 130 | + // in the history header. |
|
| 131 | + $historyHeader = $response->getHeader(self::HISTORY_HEADER); |
|
| 132 | + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); |
|
| 133 | + \array_unshift($historyHeader, $uri); |
|
| 134 | + \array_unshift($statusHeader, (string) $statusCode); |
|
| 135 | + |
|
| 136 | + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) |
|
| 137 | + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); |
|
| 138 | + } |
|
| 139 | + ); |
|
| 140 | + } |
|
| 141 | + |
|
| 142 | + /** |
|
| 143 | + * Check for too many redirects. |
|
| 144 | + * |
|
| 145 | + * @throws TooManyRedirectsException Too many redirects. |
|
| 146 | + */ |
|
| 147 | + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void |
|
| 148 | + { |
|
| 149 | + $current = $options['__redirect_count'] |
|
| 150 | + ?? 0; |
|
| 151 | + $options['__redirect_count'] = $current + 1; |
|
| 152 | + $max = $options['allow_redirects']['max']; |
|
| 153 | + |
|
| 154 | + if ($options['__redirect_count'] > $max) { |
|
| 155 | + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); |
|
| 156 | + } |
|
| 157 | + } |
|
| 158 | + |
|
| 159 | + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface |
|
| 160 | + { |
|
| 161 | + // Request modifications to apply. |
|
| 162 | + $modify = []; |
|
| 163 | + $protocols = $options['allow_redirects']['protocols']; |
|
| 164 | + |
|
| 165 | + // Use a GET request if this is an entity enclosing request and we are |
|
| 166 | + // not forcing RFC compliance, but rather emulating what all browsers |
|
| 167 | + // would do. |
|
| 168 | + $statusCode = $response->getStatusCode(); |
|
| 169 | + if ($statusCode == 303 |
|
| 170 | + || ($statusCode <= 302 && !$options['allow_redirects']['strict']) |
|
| 171 | + ) { |
|
| 172 | + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; |
|
| 173 | + $requestMethod = $request->getMethod(); |
|
| 174 | + |
|
| 175 | + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; |
|
| 176 | + $modify['body'] = ''; |
|
| 177 | + } |
|
| 178 | + |
|
| 179 | + $uri = self::redirectUri($request, $response, $protocols); |
|
| 180 | + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { |
|
| 181 | + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; |
|
| 182 | + $uri = Utils::idnUriConvert($uri, $idnOptions); |
|
| 183 | + } |
|
| 184 | + |
|
| 185 | + $modify['uri'] = $uri; |
|
| 186 | + Psr7\Message::rewindBody($request); |
|
| 187 | + |
|
| 188 | + // Add the Referer header if it is told to do so and only |
|
| 189 | + // add the header if we are not redirecting from https to http. |
|
| 190 | + if ($options['allow_redirects']['referer'] |
|
| 191 | + && $modify['uri']->getScheme() === $request->getUri()->getScheme() |
|
| 192 | + ) { |
|
| 193 | + $uri = $request->getUri()->withUserInfo(''); |
|
| 194 | + $modify['set_headers']['Referer'] = (string) $uri; |
|
| 195 | + } else { |
|
| 196 | + $modify['remove_headers'][] = 'Referer'; |
|
| 197 | + } |
|
| 198 | + |
|
| 199 | + // Remove Authorization and Cookie headers if URI is cross-origin. |
|
| 200 | + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { |
|
| 201 | + $modify['remove_headers'][] = 'Authorization'; |
|
| 202 | + $modify['remove_headers'][] = 'Cookie'; |
|
| 203 | + } |
|
| 204 | + |
|
| 205 | + return Psr7\Utils::modifyRequest($request, $modify); |
|
| 206 | + } |
|
| 207 | + |
|
| 208 | + /** |
|
| 209 | + * Set the appropriate URL on the request based on the location header. |
|
| 210 | + */ |
|
| 211 | + private static function redirectUri( |
|
| 212 | + RequestInterface $request, |
|
| 213 | + ResponseInterface $response, |
|
| 214 | + array $protocols |
|
| 215 | + ): UriInterface { |
|
| 216 | + $location = Psr7\UriResolver::resolve( |
|
| 217 | + $request->getUri(), |
|
| 218 | + new Psr7\Uri($response->getHeaderLine('Location')) |
|
| 219 | + ); |
|
| 220 | + |
|
| 221 | + // Ensure that the redirect URI is allowed based on the protocols. |
|
| 222 | + if (!\in_array($location->getScheme(), $protocols)) { |
|
| 223 | + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); |
|
| 224 | + } |
|
| 225 | + |
|
| 226 | + return $location; |
|
| 227 | + } |
|
| 228 | 228 | } |
@@ -69,7 +69,7 @@ discard block |
||
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | return $fn($request, $options) |
| 72 | - ->then(function (ResponseInterface $response) use ($request, $options) { |
|
| 72 | + ->then(function(ResponseInterface $response) use ($request, $options) { |
|
| 73 | 73 | return $this->checkRedirect($request, $options, $response); |
| 74 | 74 | }); |
| 75 | 75 | } |
@@ -79,7 +79,7 @@ discard block |
||
| 79 | 79 | */ |
| 80 | 80 | public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) |
| 81 | 81 | { |
| 82 | - if (\strpos((string) $response->getStatusCode(), '3') !== 0 |
|
| 82 | + if (\strpos((string)$response->getStatusCode(), '3') !== 0 |
|
| 83 | 83 | || !$response->hasHeader('Location') |
| 84 | 84 | ) { |
| 85 | 85 | return $response; |
@@ -110,7 +110,7 @@ discard block |
||
| 110 | 110 | if (!empty($options['allow_redirects']['track_redirects'])) { |
| 111 | 111 | return $this->withTracking( |
| 112 | 112 | $promise, |
| 113 | - (string) $nextRequest->getUri(), |
|
| 113 | + (string)$nextRequest->getUri(), |
|
| 114 | 114 | $response->getStatusCode() |
| 115 | 115 | ); |
| 116 | 116 | } |
@@ -124,14 +124,14 @@ discard block |
||
| 124 | 124 | private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface |
| 125 | 125 | { |
| 126 | 126 | return $promise->then( |
| 127 | - static function (ResponseInterface $response) use ($uri, $statusCode) { |
|
| 127 | + static function(ResponseInterface $response) use ($uri, $statusCode) { |
|
| 128 | 128 | // Note that we are pushing to the front of the list as this |
| 129 | 129 | // would be an earlier response than what is currently present |
| 130 | 130 | // in the history header. |
| 131 | 131 | $historyHeader = $response->getHeader(self::HISTORY_HEADER); |
| 132 | 132 | $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); |
| 133 | 133 | \array_unshift($historyHeader, $uri); |
| 134 | - \array_unshift($statusHeader, (string) $statusCode); |
|
| 134 | + \array_unshift($statusHeader, (string)$statusCode); |
|
| 135 | 135 | |
| 136 | 136 | return $response->withHeader(self::HISTORY_HEADER, $historyHeader) |
| 137 | 137 | ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); |
@@ -191,7 +191,7 @@ discard block |
||
| 191 | 191 | && $modify['uri']->getScheme() === $request->getUri()->getScheme() |
| 192 | 192 | ) { |
| 193 | 193 | $uri = $request->getUri()->withUserInfo(''); |
| 194 | - $modify['set_headers']['Referer'] = (string) $uri; |
|
| 194 | + $modify['set_headers']['Referer'] = (string)$uri; |
|
| 195 | 195 | } else { |
| 196 | 196 | $modify['remove_headers'][] = 'Referer'; |
| 197 | 197 | } |
@@ -17,8 +17,7 @@ |
||
| 17 | 17 | * |
| 18 | 18 | * @final |
| 19 | 19 | */ |
| 20 | -class RedirectMiddleware |
|
| 21 | -{ |
|
| 20 | +class RedirectMiddleware { |
|
| 22 | 21 | public const HISTORY_HEADER = 'X-Guzzle-Redirect-History'; |
| 23 | 22 | |
| 24 | 23 | public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History'; |
@@ -13,93 +13,93 @@ |
||
| 13 | 13 | */ |
| 14 | 14 | class PrepareBodyMiddleware |
| 15 | 15 | { |
| 16 | - /** |
|
| 17 | - * @var callable(RequestInterface, array): PromiseInterface |
|
| 18 | - */ |
|
| 19 | - private $nextHandler; |
|
| 20 | - |
|
| 21 | - /** |
|
| 22 | - * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
| 23 | - */ |
|
| 24 | - public function __construct(callable $nextHandler) |
|
| 25 | - { |
|
| 26 | - $this->nextHandler = $nextHandler; |
|
| 27 | - } |
|
| 28 | - |
|
| 29 | - public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 30 | - { |
|
| 31 | - $fn = $this->nextHandler; |
|
| 32 | - |
|
| 33 | - // Don't do anything if the request has no body. |
|
| 34 | - if ($request->getBody()->getSize() === 0) { |
|
| 35 | - return $fn($request, $options); |
|
| 36 | - } |
|
| 37 | - |
|
| 38 | - $modify = []; |
|
| 39 | - |
|
| 40 | - // Add a default content-type if possible. |
|
| 41 | - if (!$request->hasHeader('Content-Type')) { |
|
| 42 | - if ($uri = $request->getBody()->getMetadata('uri')) { |
|
| 43 | - if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { |
|
| 44 | - $modify['set_headers']['Content-Type'] = $type; |
|
| 45 | - } |
|
| 46 | - } |
|
| 47 | - } |
|
| 48 | - |
|
| 49 | - // Add a default content-length or transfer-encoding header. |
|
| 50 | - if (!$request->hasHeader('Content-Length') |
|
| 51 | - && !$request->hasHeader('Transfer-Encoding') |
|
| 52 | - ) { |
|
| 53 | - $size = $request->getBody()->getSize(); |
|
| 54 | - if ($size !== null) { |
|
| 55 | - $modify['set_headers']['Content-Length'] = $size; |
|
| 56 | - } else { |
|
| 57 | - $modify['set_headers']['Transfer-Encoding'] = 'chunked'; |
|
| 58 | - } |
|
| 59 | - } |
|
| 60 | - |
|
| 61 | - // Add the expect header if needed. |
|
| 62 | - $this->addExpectHeader($request, $options, $modify); |
|
| 63 | - |
|
| 64 | - return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); |
|
| 65 | - } |
|
| 66 | - |
|
| 67 | - /** |
|
| 68 | - * Add expect header |
|
| 69 | - */ |
|
| 70 | - private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void |
|
| 71 | - { |
|
| 72 | - // Determine if the Expect header should be used |
|
| 73 | - if ($request->hasHeader('Expect')) { |
|
| 74 | - return; |
|
| 75 | - } |
|
| 76 | - |
|
| 77 | - $expect = $options['expect'] ?? null; |
|
| 78 | - |
|
| 79 | - // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 |
|
| 80 | - if ($expect === false || $request->getProtocolVersion() < 1.1) { |
|
| 81 | - return; |
|
| 82 | - } |
|
| 83 | - |
|
| 84 | - // The expect header is unconditionally enabled |
|
| 85 | - if ($expect === true) { |
|
| 86 | - $modify['set_headers']['Expect'] = '100-Continue'; |
|
| 87 | - |
|
| 88 | - return; |
|
| 89 | - } |
|
| 90 | - |
|
| 91 | - // By default, send the expect header when the payload is > 1mb |
|
| 92 | - if ($expect === null) { |
|
| 93 | - $expect = 1048576; |
|
| 94 | - } |
|
| 95 | - |
|
| 96 | - // Always add if the body cannot be rewound, the size cannot be |
|
| 97 | - // determined, or the size is greater than the cutoff threshold |
|
| 98 | - $body = $request->getBody(); |
|
| 99 | - $size = $body->getSize(); |
|
| 100 | - |
|
| 101 | - if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
| 102 | - $modify['set_headers']['Expect'] = '100-Continue'; |
|
| 103 | - } |
|
| 104 | - } |
|
| 16 | + /** |
|
| 17 | + * @var callable(RequestInterface, array): PromiseInterface |
|
| 18 | + */ |
|
| 19 | + private $nextHandler; |
|
| 20 | + |
|
| 21 | + /** |
|
| 22 | + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. |
|
| 23 | + */ |
|
| 24 | + public function __construct(callable $nextHandler) |
|
| 25 | + { |
|
| 26 | + $this->nextHandler = $nextHandler; |
|
| 27 | + } |
|
| 28 | + |
|
| 29 | + public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 30 | + { |
|
| 31 | + $fn = $this->nextHandler; |
|
| 32 | + |
|
| 33 | + // Don't do anything if the request has no body. |
|
| 34 | + if ($request->getBody()->getSize() === 0) { |
|
| 35 | + return $fn($request, $options); |
|
| 36 | + } |
|
| 37 | + |
|
| 38 | + $modify = []; |
|
| 39 | + |
|
| 40 | + // Add a default content-type if possible. |
|
| 41 | + if (!$request->hasHeader('Content-Type')) { |
|
| 42 | + if ($uri = $request->getBody()->getMetadata('uri')) { |
|
| 43 | + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { |
|
| 44 | + $modify['set_headers']['Content-Type'] = $type; |
|
| 45 | + } |
|
| 46 | + } |
|
| 47 | + } |
|
| 48 | + |
|
| 49 | + // Add a default content-length or transfer-encoding header. |
|
| 50 | + if (!$request->hasHeader('Content-Length') |
|
| 51 | + && !$request->hasHeader('Transfer-Encoding') |
|
| 52 | + ) { |
|
| 53 | + $size = $request->getBody()->getSize(); |
|
| 54 | + if ($size !== null) { |
|
| 55 | + $modify['set_headers']['Content-Length'] = $size; |
|
| 56 | + } else { |
|
| 57 | + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; |
|
| 58 | + } |
|
| 59 | + } |
|
| 60 | + |
|
| 61 | + // Add the expect header if needed. |
|
| 62 | + $this->addExpectHeader($request, $options, $modify); |
|
| 63 | + |
|
| 64 | + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); |
|
| 65 | + } |
|
| 66 | + |
|
| 67 | + /** |
|
| 68 | + * Add expect header |
|
| 69 | + */ |
|
| 70 | + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void |
|
| 71 | + { |
|
| 72 | + // Determine if the Expect header should be used |
|
| 73 | + if ($request->hasHeader('Expect')) { |
|
| 74 | + return; |
|
| 75 | + } |
|
| 76 | + |
|
| 77 | + $expect = $options['expect'] ?? null; |
|
| 78 | + |
|
| 79 | + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 |
|
| 80 | + if ($expect === false || $request->getProtocolVersion() < 1.1) { |
|
| 81 | + return; |
|
| 82 | + } |
|
| 83 | + |
|
| 84 | + // The expect header is unconditionally enabled |
|
| 85 | + if ($expect === true) { |
|
| 86 | + $modify['set_headers']['Expect'] = '100-Continue'; |
|
| 87 | + |
|
| 88 | + return; |
|
| 89 | + } |
|
| 90 | + |
|
| 91 | + // By default, send the expect header when the payload is > 1mb |
|
| 92 | + if ($expect === null) { |
|
| 93 | + $expect = 1048576; |
|
| 94 | + } |
|
| 95 | + |
|
| 96 | + // Always add if the body cannot be rewound, the size cannot be |
|
| 97 | + // determined, or the size is greater than the cutoff threshold |
|
| 98 | + $body = $request->getBody(); |
|
| 99 | + $size = $body->getSize(); |
|
| 100 | + |
|
| 101 | + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
| 102 | + $modify['set_headers']['Expect'] = '100-Continue'; |
|
| 103 | + } |
|
| 104 | + } |
|
| 105 | 105 | } |
@@ -98,7 +98,7 @@ |
||
| 98 | 98 | $body = $request->getBody(); |
| 99 | 99 | $size = $body->getSize(); |
| 100 | 100 | |
| 101 | - if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { |
|
| 101 | + if ($size === null || $size >= (int)$expect || !$body->isSeekable()) { |
|
| 102 | 102 | $modify['set_headers']['Expect'] = '100-Continue'; |
| 103 | 103 | } |
| 104 | 104 | } |
@@ -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,230 +12,230 @@ |
||
| 12 | 12 | */ |
| 13 | 13 | trait ClientTrait |
| 14 | 14 | { |
| 15 | - /** |
|
| 16 | - * Create and send an HTTP request. |
|
| 17 | - * |
|
| 18 | - * Use an absolute path to override the base path of the client, or a |
|
| 19 | - * relative path to append to the base path of the client. The URL can |
|
| 20 | - * contain the query string as well. |
|
| 21 | - * |
|
| 22 | - * @param string $method HTTP method. |
|
| 23 | - * @param string|UriInterface $uri URI object or string. |
|
| 24 | - * @param array $options Request options to apply. |
|
| 25 | - * |
|
| 26 | - * @throws GuzzleException |
|
| 27 | - */ |
|
| 28 | - abstract public function request(string $method, $uri, array $options = []): ResponseInterface; |
|
| 29 | - |
|
| 30 | - /** |
|
| 31 | - * Create and send an HTTP GET request. |
|
| 32 | - * |
|
| 33 | - * Use an absolute path to override the base path of the client, or a |
|
| 34 | - * relative path to append to the base path of the client. The URL can |
|
| 35 | - * contain the query string as well. |
|
| 36 | - * |
|
| 37 | - * @param string|UriInterface $uri URI object or string. |
|
| 38 | - * @param array $options Request options to apply. |
|
| 39 | - * |
|
| 40 | - * @throws GuzzleException |
|
| 41 | - */ |
|
| 42 | - public function get($uri, array $options = []): ResponseInterface |
|
| 43 | - { |
|
| 44 | - return $this->request('GET', $uri, $options); |
|
| 45 | - } |
|
| 46 | - |
|
| 47 | - /** |
|
| 48 | - * Create and send an HTTP HEAD request. |
|
| 49 | - * |
|
| 50 | - * Use an absolute path to override the base path of the client, or a |
|
| 51 | - * relative path to append to the base path of the client. The URL can |
|
| 52 | - * contain the query string as well. |
|
| 53 | - * |
|
| 54 | - * @param string|UriInterface $uri URI object or string. |
|
| 55 | - * @param array $options Request options to apply. |
|
| 56 | - * |
|
| 57 | - * @throws GuzzleException |
|
| 58 | - */ |
|
| 59 | - public function head($uri, array $options = []): ResponseInterface |
|
| 60 | - { |
|
| 61 | - return $this->request('HEAD', $uri, $options); |
|
| 62 | - } |
|
| 63 | - |
|
| 64 | - /** |
|
| 65 | - * Create and send an HTTP PUT request. |
|
| 66 | - * |
|
| 67 | - * Use an absolute path to override the base path of the client, or a |
|
| 68 | - * relative path to append to the base path of the client. The URL can |
|
| 69 | - * contain the query string as well. |
|
| 70 | - * |
|
| 71 | - * @param string|UriInterface $uri URI object or string. |
|
| 72 | - * @param array $options Request options to apply. |
|
| 73 | - * |
|
| 74 | - * @throws GuzzleException |
|
| 75 | - */ |
|
| 76 | - public function put($uri, array $options = []): ResponseInterface |
|
| 77 | - { |
|
| 78 | - return $this->request('PUT', $uri, $options); |
|
| 79 | - } |
|
| 80 | - |
|
| 81 | - /** |
|
| 82 | - * Create and send an HTTP POST request. |
|
| 83 | - * |
|
| 84 | - * Use an absolute path to override the base path of the client, or a |
|
| 85 | - * relative path to append to the base path of the client. The URL can |
|
| 86 | - * contain the query string as well. |
|
| 87 | - * |
|
| 88 | - * @param string|UriInterface $uri URI object or string. |
|
| 89 | - * @param array $options Request options to apply. |
|
| 90 | - * |
|
| 91 | - * @throws GuzzleException |
|
| 92 | - */ |
|
| 93 | - public function post($uri, array $options = []): ResponseInterface |
|
| 94 | - { |
|
| 95 | - return $this->request('POST', $uri, $options); |
|
| 96 | - } |
|
| 97 | - |
|
| 98 | - /** |
|
| 99 | - * Create and send an HTTP PATCH request. |
|
| 100 | - * |
|
| 101 | - * Use an absolute path to override the base path of the client, or a |
|
| 102 | - * relative path to append to the base path of the client. The URL can |
|
| 103 | - * contain the query string as well. |
|
| 104 | - * |
|
| 105 | - * @param string|UriInterface $uri URI object or string. |
|
| 106 | - * @param array $options Request options to apply. |
|
| 107 | - * |
|
| 108 | - * @throws GuzzleException |
|
| 109 | - */ |
|
| 110 | - public function patch($uri, array $options = []): ResponseInterface |
|
| 111 | - { |
|
| 112 | - return $this->request('PATCH', $uri, $options); |
|
| 113 | - } |
|
| 114 | - |
|
| 115 | - /** |
|
| 116 | - * Create and send an HTTP DELETE request. |
|
| 117 | - * |
|
| 118 | - * Use an absolute path to override the base path of the client, or a |
|
| 119 | - * relative path to append to the base path of the client. The URL can |
|
| 120 | - * contain the query string as well. |
|
| 121 | - * |
|
| 122 | - * @param string|UriInterface $uri URI object or string. |
|
| 123 | - * @param array $options Request options to apply. |
|
| 124 | - * |
|
| 125 | - * @throws GuzzleException |
|
| 126 | - */ |
|
| 127 | - public function delete($uri, array $options = []): ResponseInterface |
|
| 128 | - { |
|
| 129 | - return $this->request('DELETE', $uri, $options); |
|
| 130 | - } |
|
| 131 | - |
|
| 132 | - /** |
|
| 133 | - * Create and send an asynchronous HTTP request. |
|
| 134 | - * |
|
| 135 | - * Use an absolute path to override the base path of the client, or a |
|
| 136 | - * relative path to append to the base path of the client. The URL can |
|
| 137 | - * contain the query string as well. Use an array to provide a URL |
|
| 138 | - * template and additional variables to use in the URL template expansion. |
|
| 139 | - * |
|
| 140 | - * @param string $method HTTP method |
|
| 141 | - * @param string|UriInterface $uri URI object or string. |
|
| 142 | - * @param array $options Request options to apply. |
|
| 143 | - */ |
|
| 144 | - abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; |
|
| 145 | - |
|
| 146 | - /** |
|
| 147 | - * Create and send an asynchronous HTTP GET request. |
|
| 148 | - * |
|
| 149 | - * Use an absolute path to override the base path of the client, or a |
|
| 150 | - * relative path to append to the base path of the client. The URL can |
|
| 151 | - * contain the query string as well. Use an array to provide a URL |
|
| 152 | - * template and additional variables to use in the URL template expansion. |
|
| 153 | - * |
|
| 154 | - * @param string|UriInterface $uri URI object or string. |
|
| 155 | - * @param array $options Request options to apply. |
|
| 156 | - */ |
|
| 157 | - public function getAsync($uri, array $options = []): PromiseInterface |
|
| 158 | - { |
|
| 159 | - return $this->requestAsync('GET', $uri, $options); |
|
| 160 | - } |
|
| 161 | - |
|
| 162 | - /** |
|
| 163 | - * Create and send an asynchronous HTTP HEAD request. |
|
| 164 | - * |
|
| 165 | - * Use an absolute path to override the base path of the client, or a |
|
| 166 | - * relative path to append to the base path of the client. The URL can |
|
| 167 | - * contain the query string as well. Use an array to provide a URL |
|
| 168 | - * template and additional variables to use in the URL template expansion. |
|
| 169 | - * |
|
| 170 | - * @param string|UriInterface $uri URI object or string. |
|
| 171 | - * @param array $options Request options to apply. |
|
| 172 | - */ |
|
| 173 | - public function headAsync($uri, array $options = []): PromiseInterface |
|
| 174 | - { |
|
| 175 | - return $this->requestAsync('HEAD', $uri, $options); |
|
| 176 | - } |
|
| 177 | - |
|
| 178 | - /** |
|
| 179 | - * Create and send an asynchronous HTTP PUT request. |
|
| 180 | - * |
|
| 181 | - * Use an absolute path to override the base path of the client, or a |
|
| 182 | - * relative path to append to the base path of the client. The URL can |
|
| 183 | - * contain the query string as well. Use an array to provide a URL |
|
| 184 | - * template and additional variables to use in the URL template expansion. |
|
| 185 | - * |
|
| 186 | - * @param string|UriInterface $uri URI object or string. |
|
| 187 | - * @param array $options Request options to apply. |
|
| 188 | - */ |
|
| 189 | - public function putAsync($uri, array $options = []): PromiseInterface |
|
| 190 | - { |
|
| 191 | - return $this->requestAsync('PUT', $uri, $options); |
|
| 192 | - } |
|
| 193 | - |
|
| 194 | - /** |
|
| 195 | - * Create and send an asynchronous HTTP POST request. |
|
| 196 | - * |
|
| 197 | - * Use an absolute path to override the base path of the client, or a |
|
| 198 | - * relative path to append to the base path of the client. The URL can |
|
| 199 | - * contain the query string as well. Use an array to provide a URL |
|
| 200 | - * template and additional variables to use in the URL template expansion. |
|
| 201 | - * |
|
| 202 | - * @param string|UriInterface $uri URI object or string. |
|
| 203 | - * @param array $options Request options to apply. |
|
| 204 | - */ |
|
| 205 | - public function postAsync($uri, array $options = []): PromiseInterface |
|
| 206 | - { |
|
| 207 | - return $this->requestAsync('POST', $uri, $options); |
|
| 208 | - } |
|
| 209 | - |
|
| 210 | - /** |
|
| 211 | - * Create and send an asynchronous HTTP PATCH request. |
|
| 212 | - * |
|
| 213 | - * Use an absolute path to override the base path of the client, or a |
|
| 214 | - * relative path to append to the base path of the client. The URL can |
|
| 215 | - * contain the query string as well. Use an array to provide a URL |
|
| 216 | - * template and additional variables to use in the URL template expansion. |
|
| 217 | - * |
|
| 218 | - * @param string|UriInterface $uri URI object or string. |
|
| 219 | - * @param array $options Request options to apply. |
|
| 220 | - */ |
|
| 221 | - public function patchAsync($uri, array $options = []): PromiseInterface |
|
| 222 | - { |
|
| 223 | - return $this->requestAsync('PATCH', $uri, $options); |
|
| 224 | - } |
|
| 225 | - |
|
| 226 | - /** |
|
| 227 | - * Create and send an asynchronous HTTP DELETE request. |
|
| 228 | - * |
|
| 229 | - * Use an absolute path to override the base path of the client, or a |
|
| 230 | - * relative path to append to the base path of the client. The URL can |
|
| 231 | - * contain the query string as well. Use an array to provide a URL |
|
| 232 | - * template and additional variables to use in the URL template expansion. |
|
| 233 | - * |
|
| 234 | - * @param string|UriInterface $uri URI object or string. |
|
| 235 | - * @param array $options Request options to apply. |
|
| 236 | - */ |
|
| 237 | - public function deleteAsync($uri, array $options = []): PromiseInterface |
|
| 238 | - { |
|
| 239 | - return $this->requestAsync('DELETE', $uri, $options); |
|
| 240 | - } |
|
| 15 | + /** |
|
| 16 | + * Create and send an HTTP request. |
|
| 17 | + * |
|
| 18 | + * Use an absolute path to override the base path of the client, or a |
|
| 19 | + * relative path to append to the base path of the client. The URL can |
|
| 20 | + * contain the query string as well. |
|
| 21 | + * |
|
| 22 | + * @param string $method HTTP method. |
|
| 23 | + * @param string|UriInterface $uri URI object or string. |
|
| 24 | + * @param array $options Request options to apply. |
|
| 25 | + * |
|
| 26 | + * @throws GuzzleException |
|
| 27 | + */ |
|
| 28 | + abstract public function request(string $method, $uri, array $options = []): ResponseInterface; |
|
| 29 | + |
|
| 30 | + /** |
|
| 31 | + * Create and send an HTTP GET request. |
|
| 32 | + * |
|
| 33 | + * Use an absolute path to override the base path of the client, or a |
|
| 34 | + * relative path to append to the base path of the client. The URL can |
|
| 35 | + * contain the query string as well. |
|
| 36 | + * |
|
| 37 | + * @param string|UriInterface $uri URI object or string. |
|
| 38 | + * @param array $options Request options to apply. |
|
| 39 | + * |
|
| 40 | + * @throws GuzzleException |
|
| 41 | + */ |
|
| 42 | + public function get($uri, array $options = []): ResponseInterface |
|
| 43 | + { |
|
| 44 | + return $this->request('GET', $uri, $options); |
|
| 45 | + } |
|
| 46 | + |
|
| 47 | + /** |
|
| 48 | + * Create and send an HTTP HEAD request. |
|
| 49 | + * |
|
| 50 | + * Use an absolute path to override the base path of the client, or a |
|
| 51 | + * relative path to append to the base path of the client. The URL can |
|
| 52 | + * contain the query string as well. |
|
| 53 | + * |
|
| 54 | + * @param string|UriInterface $uri URI object or string. |
|
| 55 | + * @param array $options Request options to apply. |
|
| 56 | + * |
|
| 57 | + * @throws GuzzleException |
|
| 58 | + */ |
|
| 59 | + public function head($uri, array $options = []): ResponseInterface |
|
| 60 | + { |
|
| 61 | + return $this->request('HEAD', $uri, $options); |
|
| 62 | + } |
|
| 63 | + |
|
| 64 | + /** |
|
| 65 | + * Create and send an HTTP PUT request. |
|
| 66 | + * |
|
| 67 | + * Use an absolute path to override the base path of the client, or a |
|
| 68 | + * relative path to append to the base path of the client. The URL can |
|
| 69 | + * contain the query string as well. |
|
| 70 | + * |
|
| 71 | + * @param string|UriInterface $uri URI object or string. |
|
| 72 | + * @param array $options Request options to apply. |
|
| 73 | + * |
|
| 74 | + * @throws GuzzleException |
|
| 75 | + */ |
|
| 76 | + public function put($uri, array $options = []): ResponseInterface |
|
| 77 | + { |
|
| 78 | + return $this->request('PUT', $uri, $options); |
|
| 79 | + } |
|
| 80 | + |
|
| 81 | + /** |
|
| 82 | + * Create and send an HTTP POST request. |
|
| 83 | + * |
|
| 84 | + * Use an absolute path to override the base path of the client, or a |
|
| 85 | + * relative path to append to the base path of the client. The URL can |
|
| 86 | + * contain the query string as well. |
|
| 87 | + * |
|
| 88 | + * @param string|UriInterface $uri URI object or string. |
|
| 89 | + * @param array $options Request options to apply. |
|
| 90 | + * |
|
| 91 | + * @throws GuzzleException |
|
| 92 | + */ |
|
| 93 | + public function post($uri, array $options = []): ResponseInterface |
|
| 94 | + { |
|
| 95 | + return $this->request('POST', $uri, $options); |
|
| 96 | + } |
|
| 97 | + |
|
| 98 | + /** |
|
| 99 | + * Create and send an HTTP PATCH request. |
|
| 100 | + * |
|
| 101 | + * Use an absolute path to override the base path of the client, or a |
|
| 102 | + * relative path to append to the base path of the client. The URL can |
|
| 103 | + * contain the query string as well. |
|
| 104 | + * |
|
| 105 | + * @param string|UriInterface $uri URI object or string. |
|
| 106 | + * @param array $options Request options to apply. |
|
| 107 | + * |
|
| 108 | + * @throws GuzzleException |
|
| 109 | + */ |
|
| 110 | + public function patch($uri, array $options = []): ResponseInterface |
|
| 111 | + { |
|
| 112 | + return $this->request('PATCH', $uri, $options); |
|
| 113 | + } |
|
| 114 | + |
|
| 115 | + /** |
|
| 116 | + * Create and send an HTTP DELETE request. |
|
| 117 | + * |
|
| 118 | + * Use an absolute path to override the base path of the client, or a |
|
| 119 | + * relative path to append to the base path of the client. The URL can |
|
| 120 | + * contain the query string as well. |
|
| 121 | + * |
|
| 122 | + * @param string|UriInterface $uri URI object or string. |
|
| 123 | + * @param array $options Request options to apply. |
|
| 124 | + * |
|
| 125 | + * @throws GuzzleException |
|
| 126 | + */ |
|
| 127 | + public function delete($uri, array $options = []): ResponseInterface |
|
| 128 | + { |
|
| 129 | + return $this->request('DELETE', $uri, $options); |
|
| 130 | + } |
|
| 131 | + |
|
| 132 | + /** |
|
| 133 | + * Create and send an asynchronous HTTP request. |
|
| 134 | + * |
|
| 135 | + * Use an absolute path to override the base path of the client, or a |
|
| 136 | + * relative path to append to the base path of the client. The URL can |
|
| 137 | + * contain the query string as well. Use an array to provide a URL |
|
| 138 | + * template and additional variables to use in the URL template expansion. |
|
| 139 | + * |
|
| 140 | + * @param string $method HTTP method |
|
| 141 | + * @param string|UriInterface $uri URI object or string. |
|
| 142 | + * @param array $options Request options to apply. |
|
| 143 | + */ |
|
| 144 | + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; |
|
| 145 | + |
|
| 146 | + /** |
|
| 147 | + * Create and send an asynchronous HTTP GET request. |
|
| 148 | + * |
|
| 149 | + * Use an absolute path to override the base path of the client, or a |
|
| 150 | + * relative path to append to the base path of the client. The URL can |
|
| 151 | + * contain the query string as well. Use an array to provide a URL |
|
| 152 | + * template and additional variables to use in the URL template expansion. |
|
| 153 | + * |
|
| 154 | + * @param string|UriInterface $uri URI object or string. |
|
| 155 | + * @param array $options Request options to apply. |
|
| 156 | + */ |
|
| 157 | + public function getAsync($uri, array $options = []): PromiseInterface |
|
| 158 | + { |
|
| 159 | + return $this->requestAsync('GET', $uri, $options); |
|
| 160 | + } |
|
| 161 | + |
|
| 162 | + /** |
|
| 163 | + * Create and send an asynchronous HTTP HEAD request. |
|
| 164 | + * |
|
| 165 | + * Use an absolute path to override the base path of the client, or a |
|
| 166 | + * relative path to append to the base path of the client. The URL can |
|
| 167 | + * contain the query string as well. Use an array to provide a URL |
|
| 168 | + * template and additional variables to use in the URL template expansion. |
|
| 169 | + * |
|
| 170 | + * @param string|UriInterface $uri URI object or string. |
|
| 171 | + * @param array $options Request options to apply. |
|
| 172 | + */ |
|
| 173 | + public function headAsync($uri, array $options = []): PromiseInterface |
|
| 174 | + { |
|
| 175 | + return $this->requestAsync('HEAD', $uri, $options); |
|
| 176 | + } |
|
| 177 | + |
|
| 178 | + /** |
|
| 179 | + * Create and send an asynchronous HTTP PUT request. |
|
| 180 | + * |
|
| 181 | + * Use an absolute path to override the base path of the client, or a |
|
| 182 | + * relative path to append to the base path of the client. The URL can |
|
| 183 | + * contain the query string as well. Use an array to provide a URL |
|
| 184 | + * template and additional variables to use in the URL template expansion. |
|
| 185 | + * |
|
| 186 | + * @param string|UriInterface $uri URI object or string. |
|
| 187 | + * @param array $options Request options to apply. |
|
| 188 | + */ |
|
| 189 | + public function putAsync($uri, array $options = []): PromiseInterface |
|
| 190 | + { |
|
| 191 | + return $this->requestAsync('PUT', $uri, $options); |
|
| 192 | + } |
|
| 193 | + |
|
| 194 | + /** |
|
| 195 | + * Create and send an asynchronous HTTP POST request. |
|
| 196 | + * |
|
| 197 | + * Use an absolute path to override the base path of the client, or a |
|
| 198 | + * relative path to append to the base path of the client. The URL can |
|
| 199 | + * contain the query string as well. Use an array to provide a URL |
|
| 200 | + * template and additional variables to use in the URL template expansion. |
|
| 201 | + * |
|
| 202 | + * @param string|UriInterface $uri URI object or string. |
|
| 203 | + * @param array $options Request options to apply. |
|
| 204 | + */ |
|
| 205 | + public function postAsync($uri, array $options = []): PromiseInterface |
|
| 206 | + { |
|
| 207 | + return $this->requestAsync('POST', $uri, $options); |
|
| 208 | + } |
|
| 209 | + |
|
| 210 | + /** |
|
| 211 | + * Create and send an asynchronous HTTP PATCH request. |
|
| 212 | + * |
|
| 213 | + * Use an absolute path to override the base path of the client, or a |
|
| 214 | + * relative path to append to the base path of the client. The URL can |
|
| 215 | + * contain the query string as well. Use an array to provide a URL |
|
| 216 | + * template and additional variables to use in the URL template expansion. |
|
| 217 | + * |
|
| 218 | + * @param string|UriInterface $uri URI object or string. |
|
| 219 | + * @param array $options Request options to apply. |
|
| 220 | + */ |
|
| 221 | + public function patchAsync($uri, array $options = []): PromiseInterface |
|
| 222 | + { |
|
| 223 | + return $this->requestAsync('PATCH', $uri, $options); |
|
| 224 | + } |
|
| 225 | + |
|
| 226 | + /** |
|
| 227 | + * Create and send an asynchronous HTTP DELETE request. |
|
| 228 | + * |
|
| 229 | + * Use an absolute path to override the base path of the client, or a |
|
| 230 | + * relative path to append to the base path of the client. The URL can |
|
| 231 | + * contain the query string as well. Use an array to provide a URL |
|
| 232 | + * template and additional variables to use in the URL template expansion. |
|
| 233 | + * |
|
| 234 | + * @param string|UriInterface $uri URI object or string. |
|
| 235 | + * @param array $options Request options to apply. |
|
| 236 | + */ |
|
| 237 | + public function deleteAsync($uri, array $options = []): PromiseInterface |
|
| 238 | + { |
|
| 239 | + return $this->requestAsync('DELETE', $uri, $options); |
|
| 240 | + } |
|
| 241 | 241 | } |
@@ -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 | * |
@@ -6,23 +6,23 @@ |
||
| 6 | 6 | |
| 7 | 7 | final class BodySummarizer implements BodySummarizerInterface |
| 8 | 8 | { |
| 9 | - /** |
|
| 10 | - * @var int|null |
|
| 11 | - */ |
|
| 12 | - private $truncateAt; |
|
| 9 | + /** |
|
| 10 | + * @var int|null |
|
| 11 | + */ |
|
| 12 | + private $truncateAt; |
|
| 13 | 13 | |
| 14 | - public function __construct(int $truncateAt = null) |
|
| 15 | - { |
|
| 16 | - $this->truncateAt = $truncateAt; |
|
| 17 | - } |
|
| 14 | + public function __construct(int $truncateAt = null) |
|
| 15 | + { |
|
| 16 | + $this->truncateAt = $truncateAt; |
|
| 17 | + } |
|
| 18 | 18 | |
| 19 | - /** |
|
| 20 | - * Returns a summarized message body. |
|
| 21 | - */ |
|
| 22 | - public function summarize(MessageInterface $message): ?string |
|
| 23 | - { |
|
| 24 | - return $this->truncateAt === null |
|
| 25 | - ? \OCA\FullTextSearch_Elasticsearch\Vendor\GuzzleHttp\Psr7\Message::bodySummary($message) |
|
| 26 | - : \OCA\FullTextSearch_Elasticsearch\Vendor\GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); |
|
| 27 | - } |
|
| 19 | + /** |
|
| 20 | + * Returns a summarized message body. |
|
| 21 | + */ |
|
| 22 | + public function summarize(MessageInterface $message): ?string |
|
| 23 | + { |
|
| 24 | + return $this->truncateAt === null |
|
| 25 | + ? \OCA\FullTextSearch_Elasticsearch\Vendor\GuzzleHttp\Psr7\Message::bodySummary($message) |
|
| 26 | + : \OCA\FullTextSearch_Elasticsearch\Vendor\GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); |
|
| 27 | + } |
|
| 28 | 28 | } |
@@ -4,8 +4,7 @@ |
||
| 4 | 4 | |
| 5 | 5 | use OCA\FullTextSearch_Elasticsearch\Vendor\Psr\Http\Message\MessageInterface; |
| 6 | 6 | |
| 7 | -final class BodySummarizer implements BodySummarizerInterface |
|
| 8 | -{ |
|
| 7 | +final class BodySummarizer implements BodySummarizerInterface { |
|
| 9 | 8 | /** |
| 10 | 9 | * @var int|null |
| 11 | 10 | */ |
@@ -13,72 +13,72 @@ |
||
| 13 | 13 | */ |
| 14 | 14 | interface ClientInterface |
| 15 | 15 | { |
| 16 | - /** |
|
| 17 | - * The Guzzle major version. |
|
| 18 | - */ |
|
| 19 | - public const MAJOR_VERSION = 7; |
|
| 16 | + /** |
|
| 17 | + * The Guzzle major version. |
|
| 18 | + */ |
|
| 19 | + public const MAJOR_VERSION = 7; |
|
| 20 | 20 | |
| 21 | - /** |
|
| 22 | - * Send an HTTP request. |
|
| 23 | - * |
|
| 24 | - * @param RequestInterface $request Request to send |
|
| 25 | - * @param array $options Request options to apply to the given |
|
| 26 | - * request and to the transfer. |
|
| 27 | - * |
|
| 28 | - * @throws GuzzleException |
|
| 29 | - */ |
|
| 30 | - public function send(RequestInterface $request, array $options = []): ResponseInterface; |
|
| 21 | + /** |
|
| 22 | + * Send an HTTP request. |
|
| 23 | + * |
|
| 24 | + * @param RequestInterface $request Request to send |
|
| 25 | + * @param array $options Request options to apply to the given |
|
| 26 | + * request and to the transfer. |
|
| 27 | + * |
|
| 28 | + * @throws GuzzleException |
|
| 29 | + */ |
|
| 30 | + public function send(RequestInterface $request, array $options = []): ResponseInterface; |
|
| 31 | 31 | |
| 32 | - /** |
|
| 33 | - * Asynchronously send an HTTP request. |
|
| 34 | - * |
|
| 35 | - * @param RequestInterface $request Request to send |
|
| 36 | - * @param array $options Request options to apply to the given |
|
| 37 | - * request and to the transfer. |
|
| 38 | - */ |
|
| 39 | - public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface; |
|
| 32 | + /** |
|
| 33 | + * Asynchronously send an HTTP request. |
|
| 34 | + * |
|
| 35 | + * @param RequestInterface $request Request to send |
|
| 36 | + * @param array $options Request options to apply to the given |
|
| 37 | + * request and to the transfer. |
|
| 38 | + */ |
|
| 39 | + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface; |
|
| 40 | 40 | |
| 41 | - /** |
|
| 42 | - * Create and send an HTTP request. |
|
| 43 | - * |
|
| 44 | - * Use an absolute path to override the base path of the client, or a |
|
| 45 | - * relative path to append to the base path of the client. The URL can |
|
| 46 | - * contain the query string as well. |
|
| 47 | - * |
|
| 48 | - * @param string $method HTTP method. |
|
| 49 | - * @param string|UriInterface $uri URI object or string. |
|
| 50 | - * @param array $options Request options to apply. |
|
| 51 | - * |
|
| 52 | - * @throws GuzzleException |
|
| 53 | - */ |
|
| 54 | - public function request(string $method, $uri, array $options = []): ResponseInterface; |
|
| 41 | + /** |
|
| 42 | + * Create and send an HTTP request. |
|
| 43 | + * |
|
| 44 | + * Use an absolute path to override the base path of the client, or a |
|
| 45 | + * relative path to append to the base path of the client. The URL can |
|
| 46 | + * contain the query string as well. |
|
| 47 | + * |
|
| 48 | + * @param string $method HTTP method. |
|
| 49 | + * @param string|UriInterface $uri URI object or string. |
|
| 50 | + * @param array $options Request options to apply. |
|
| 51 | + * |
|
| 52 | + * @throws GuzzleException |
|
| 53 | + */ |
|
| 54 | + public function request(string $method, $uri, array $options = []): ResponseInterface; |
|
| 55 | 55 | |
| 56 | - /** |
|
| 57 | - * Create and send an asynchronous HTTP request. |
|
| 58 | - * |
|
| 59 | - * Use an absolute path to override the base path of the client, or a |
|
| 60 | - * relative path to append to the base path of the client. The URL can |
|
| 61 | - * contain the query string as well. Use an array to provide a URL |
|
| 62 | - * template and additional variables to use in the URL template expansion. |
|
| 63 | - * |
|
| 64 | - * @param string $method HTTP method |
|
| 65 | - * @param string|UriInterface $uri URI object or string. |
|
| 66 | - * @param array $options Request options to apply. |
|
| 67 | - */ |
|
| 68 | - public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; |
|
| 56 | + /** |
|
| 57 | + * Create and send an asynchronous HTTP request. |
|
| 58 | + * |
|
| 59 | + * Use an absolute path to override the base path of the client, or a |
|
| 60 | + * relative path to append to the base path of the client. The URL can |
|
| 61 | + * contain the query string as well. Use an array to provide a URL |
|
| 62 | + * template and additional variables to use in the URL template expansion. |
|
| 63 | + * |
|
| 64 | + * @param string $method HTTP method |
|
| 65 | + * @param string|UriInterface $uri URI object or string. |
|
| 66 | + * @param array $options Request options to apply. |
|
| 67 | + */ |
|
| 68 | + public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; |
|
| 69 | 69 | |
| 70 | - /** |
|
| 71 | - * Get a client configuration option. |
|
| 72 | - * |
|
| 73 | - * These options include default request options of the client, a "handler" |
|
| 74 | - * (if utilized by the concrete client), and a "base_uri" if utilized by |
|
| 75 | - * the concrete client. |
|
| 76 | - * |
|
| 77 | - * @param string|null $option The config option to retrieve. |
|
| 78 | - * |
|
| 79 | - * @return mixed |
|
| 80 | - * |
|
| 81 | - * @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0. |
|
| 82 | - */ |
|
| 83 | - public function getConfig(string $option = null); |
|
| 70 | + /** |
|
| 71 | + * Get a client configuration option. |
|
| 72 | + * |
|
| 73 | + * These options include default request options of the client, a "handler" |
|
| 74 | + * (if utilized by the concrete client), and a "base_uri" if utilized by |
|
| 75 | + * the concrete client. |
|
| 76 | + * |
|
| 77 | + * @param string|null $option The config option to retrieve. |
|
| 78 | + * |
|
| 79 | + * @return mixed |
|
| 80 | + * |
|
| 81 | + * @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0. |
|
| 82 | + */ |
|
| 83 | + public function getConfig(string $option = null); |
|
| 84 | 84 | } |
@@ -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 | */ |
@@ -22,594 +22,594 @@ |
||
| 22 | 22 | */ |
| 23 | 23 | class StreamHandler |
| 24 | 24 | { |
| 25 | - /** |
|
| 26 | - * @var array |
|
| 27 | - */ |
|
| 28 | - private $lastHeaders = []; |
|
| 29 | - |
|
| 30 | - /** |
|
| 31 | - * Sends an HTTP request. |
|
| 32 | - * |
|
| 33 | - * @param RequestInterface $request Request to send. |
|
| 34 | - * @param array $options Request transfer options. |
|
| 35 | - */ |
|
| 36 | - public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 37 | - { |
|
| 38 | - // Sleep if there is a delay specified. |
|
| 39 | - if (isset($options['delay'])) { |
|
| 40 | - \usleep($options['delay'] * 1000); |
|
| 41 | - } |
|
| 42 | - |
|
| 43 | - $startTime = isset($options['on_stats']) ? Utils::currentTime() : null; |
|
| 44 | - |
|
| 45 | - try { |
|
| 46 | - // Does not support the expect header. |
|
| 47 | - $request = $request->withoutHeader('Expect'); |
|
| 48 | - |
|
| 49 | - // Append a content-length header if body size is zero to match |
|
| 50 | - // cURL's behavior. |
|
| 51 | - if (0 === $request->getBody()->getSize()) { |
|
| 52 | - $request = $request->withHeader('Content-Length', '0'); |
|
| 53 | - } |
|
| 54 | - |
|
| 55 | - return $this->createResponse( |
|
| 56 | - $request, |
|
| 57 | - $options, |
|
| 58 | - $this->createStream($request, $options), |
|
| 59 | - $startTime |
|
| 60 | - ); |
|
| 61 | - } catch (\InvalidArgumentException $e) { |
|
| 62 | - throw $e; |
|
| 63 | - } catch (\Exception $e) { |
|
| 64 | - // Determine if the error was a networking error. |
|
| 65 | - $message = $e->getMessage(); |
|
| 66 | - // This list can probably get more comprehensive. |
|
| 67 | - if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed |
|
| 68 | - || false !== \strpos($message, 'Connection refused') |
|
| 69 | - || false !== \strpos($message, "couldn't connect to host") // error on HHVM |
|
| 70 | - || false !== \strpos($message, 'connection attempt failed') |
|
| 71 | - ) { |
|
| 72 | - $e = new ConnectException($e->getMessage(), $request, $e); |
|
| 73 | - } else { |
|
| 74 | - $e = RequestException::wrapException($request, $e); |
|
| 75 | - } |
|
| 76 | - $this->invokeStats($options, $request, $startTime, null, $e); |
|
| 77 | - |
|
| 78 | - return P\Create::rejectionFor($e); |
|
| 79 | - } |
|
| 80 | - } |
|
| 81 | - |
|
| 82 | - private function invokeStats( |
|
| 83 | - array $options, |
|
| 84 | - RequestInterface $request, |
|
| 85 | - ?float $startTime, |
|
| 86 | - ResponseInterface $response = null, |
|
| 87 | - \Throwable $error = null |
|
| 88 | - ): void { |
|
| 89 | - if (isset($options['on_stats'])) { |
|
| 90 | - $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); |
|
| 91 | - ($options['on_stats'])($stats); |
|
| 92 | - } |
|
| 93 | - } |
|
| 94 | - |
|
| 95 | - /** |
|
| 96 | - * @param resource $stream |
|
| 97 | - */ |
|
| 98 | - private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface |
|
| 99 | - { |
|
| 100 | - $hdrs = $this->lastHeaders; |
|
| 101 | - $this->lastHeaders = []; |
|
| 102 | - |
|
| 103 | - try { |
|
| 104 | - [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); |
|
| 105 | - } catch (\Exception $e) { |
|
| 106 | - return P\Create::rejectionFor( |
|
| 107 | - new RequestException('An error was encountered while creating the response', $request, null, $e) |
|
| 108 | - ); |
|
| 109 | - } |
|
| 110 | - |
|
| 111 | - [$stream, $headers] = $this->checkDecode($options, $headers, $stream); |
|
| 112 | - $stream = Psr7\Utils::streamFor($stream); |
|
| 113 | - $sink = $stream; |
|
| 114 | - |
|
| 115 | - if (\strcasecmp('HEAD', $request->getMethod())) { |
|
| 116 | - $sink = $this->createSink($stream, $options); |
|
| 117 | - } |
|
| 118 | - |
|
| 119 | - try { |
|
| 120 | - $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); |
|
| 121 | - } catch (\Exception $e) { |
|
| 122 | - return P\Create::rejectionFor( |
|
| 123 | - new RequestException('An error was encountered while creating the response', $request, null, $e) |
|
| 124 | - ); |
|
| 125 | - } |
|
| 126 | - |
|
| 127 | - if (isset($options['on_headers'])) { |
|
| 128 | - try { |
|
| 129 | - $options['on_headers']($response); |
|
| 130 | - } catch (\Exception $e) { |
|
| 131 | - return P\Create::rejectionFor( |
|
| 132 | - new RequestException('An error was encountered during the on_headers event', $request, $response, $e) |
|
| 133 | - ); |
|
| 134 | - } |
|
| 135 | - } |
|
| 136 | - |
|
| 137 | - // Do not drain when the request is a HEAD request because they have |
|
| 138 | - // no body. |
|
| 139 | - if ($sink !== $stream) { |
|
| 140 | - $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); |
|
| 141 | - } |
|
| 142 | - |
|
| 143 | - $this->invokeStats($options, $request, $startTime, $response, null); |
|
| 144 | - |
|
| 145 | - return new FulfilledPromise($response); |
|
| 146 | - } |
|
| 147 | - |
|
| 148 | - private function createSink(StreamInterface $stream, array $options): StreamInterface |
|
| 149 | - { |
|
| 150 | - if (!empty($options['stream'])) { |
|
| 151 | - return $stream; |
|
| 152 | - } |
|
| 153 | - |
|
| 154 | - $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); |
|
| 155 | - |
|
| 156 | - return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); |
|
| 157 | - } |
|
| 158 | - |
|
| 159 | - /** |
|
| 160 | - * @param resource $stream |
|
| 161 | - */ |
|
| 162 | - private function checkDecode(array $options, array $headers, $stream): array |
|
| 163 | - { |
|
| 164 | - // Automatically decode responses when instructed. |
|
| 165 | - if (!empty($options['decode_content'])) { |
|
| 166 | - $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
| 167 | - if (isset($normalizedKeys['content-encoding'])) { |
|
| 168 | - $encoding = $headers[$normalizedKeys['content-encoding']]; |
|
| 169 | - if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { |
|
| 170 | - $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); |
|
| 171 | - $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
| 172 | - |
|
| 173 | - // Remove content-encoding header |
|
| 174 | - unset($headers[$normalizedKeys['content-encoding']]); |
|
| 175 | - |
|
| 176 | - // Fix content-length header |
|
| 177 | - if (isset($normalizedKeys['content-length'])) { |
|
| 178 | - $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
| 179 | - $length = (int) $stream->getSize(); |
|
| 180 | - if ($length === 0) { |
|
| 181 | - unset($headers[$normalizedKeys['content-length']]); |
|
| 182 | - } else { |
|
| 183 | - $headers[$normalizedKeys['content-length']] = [$length]; |
|
| 184 | - } |
|
| 185 | - } |
|
| 186 | - } |
|
| 187 | - } |
|
| 188 | - } |
|
| 189 | - |
|
| 190 | - return [$stream, $headers]; |
|
| 191 | - } |
|
| 192 | - |
|
| 193 | - /** |
|
| 194 | - * Drains the source stream into the "sink" client option. |
|
| 195 | - * |
|
| 196 | - * @param string $contentLength Header specifying the amount of |
|
| 197 | - * data to read. |
|
| 198 | - * |
|
| 199 | - * @throws \RuntimeException when the sink option is invalid. |
|
| 200 | - */ |
|
| 201 | - private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface |
|
| 202 | - { |
|
| 203 | - // If a content-length header is provided, then stop reading once |
|
| 204 | - // that number of bytes has been read. This can prevent infinitely |
|
| 205 | - // reading from a stream when dealing with servers that do not honor |
|
| 206 | - // Connection: Close headers. |
|
| 207 | - Psr7\Utils::copyToStream( |
|
| 208 | - $source, |
|
| 209 | - $sink, |
|
| 210 | - (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 |
|
| 211 | - ); |
|
| 212 | - |
|
| 213 | - $sink->seek(0); |
|
| 214 | - $source->close(); |
|
| 215 | - |
|
| 216 | - return $sink; |
|
| 217 | - } |
|
| 218 | - |
|
| 219 | - /** |
|
| 220 | - * Create a resource and check to ensure it was created successfully |
|
| 221 | - * |
|
| 222 | - * @param callable $callback Callable that returns stream resource |
|
| 223 | - * |
|
| 224 | - * @return resource |
|
| 225 | - * |
|
| 226 | - * @throws \RuntimeException on error |
|
| 227 | - */ |
|
| 228 | - private function createResource(callable $callback) |
|
| 229 | - { |
|
| 230 | - $errors = []; |
|
| 231 | - \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { |
|
| 232 | - $errors[] = [ |
|
| 233 | - 'message' => $msg, |
|
| 234 | - 'file' => $file, |
|
| 235 | - 'line' => $line, |
|
| 236 | - ]; |
|
| 237 | - |
|
| 238 | - return true; |
|
| 239 | - }); |
|
| 240 | - |
|
| 241 | - try { |
|
| 242 | - $resource = $callback(); |
|
| 243 | - } finally { |
|
| 244 | - \restore_error_handler(); |
|
| 245 | - } |
|
| 246 | - |
|
| 247 | - if (!$resource) { |
|
| 248 | - $message = 'Error creating resource: '; |
|
| 249 | - foreach ($errors as $err) { |
|
| 250 | - foreach ($err as $key => $value) { |
|
| 251 | - $message .= "[$key] $value".\PHP_EOL; |
|
| 252 | - } |
|
| 253 | - } |
|
| 254 | - throw new \RuntimeException(\trim($message)); |
|
| 255 | - } |
|
| 256 | - |
|
| 257 | - return $resource; |
|
| 258 | - } |
|
| 259 | - |
|
| 260 | - /** |
|
| 261 | - * @return resource |
|
| 262 | - */ |
|
| 263 | - private function createStream(RequestInterface $request, array $options) |
|
| 264 | - { |
|
| 265 | - static $methods; |
|
| 266 | - if (!$methods) { |
|
| 267 | - $methods = \array_flip(\get_class_methods(__CLASS__)); |
|
| 268 | - } |
|
| 269 | - |
|
| 270 | - if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { |
|
| 271 | - throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); |
|
| 272 | - } |
|
| 273 | - |
|
| 274 | - // HTTP/1.1 streams using the PHP stream wrapper require a |
|
| 275 | - // Connection: close header |
|
| 276 | - if ($request->getProtocolVersion() == '1.1' |
|
| 277 | - && !$request->hasHeader('Connection') |
|
| 278 | - ) { |
|
| 279 | - $request = $request->withHeader('Connection', 'close'); |
|
| 280 | - } |
|
| 281 | - |
|
| 282 | - // Ensure SSL is verified by default |
|
| 283 | - if (!isset($options['verify'])) { |
|
| 284 | - $options['verify'] = true; |
|
| 285 | - } |
|
| 286 | - |
|
| 287 | - $params = []; |
|
| 288 | - $context = $this->getDefaultContext($request); |
|
| 289 | - |
|
| 290 | - if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { |
|
| 291 | - throw new \InvalidArgumentException('on_headers must be callable'); |
|
| 292 | - } |
|
| 293 | - |
|
| 294 | - if (!empty($options)) { |
|
| 295 | - foreach ($options as $key => $value) { |
|
| 296 | - $method = "add_{$key}"; |
|
| 297 | - if (isset($methods[$method])) { |
|
| 298 | - $this->{$method}($request, $context, $value, $params); |
|
| 299 | - } |
|
| 300 | - } |
|
| 301 | - } |
|
| 302 | - |
|
| 303 | - if (isset($options['stream_context'])) { |
|
| 304 | - if (!\is_array($options['stream_context'])) { |
|
| 305 | - throw new \InvalidArgumentException('stream_context must be an array'); |
|
| 306 | - } |
|
| 307 | - $context = \array_replace_recursive($context, $options['stream_context']); |
|
| 308 | - } |
|
| 309 | - |
|
| 310 | - // Microsoft NTLM authentication only supported with curl handler |
|
| 311 | - if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { |
|
| 312 | - throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); |
|
| 313 | - } |
|
| 314 | - |
|
| 315 | - $uri = $this->resolveHost($request, $options); |
|
| 316 | - |
|
| 317 | - $contextResource = $this->createResource( |
|
| 318 | - static function () use ($context, $params) { |
|
| 319 | - return \stream_context_create($context, $params); |
|
| 320 | - } |
|
| 321 | - ); |
|
| 322 | - |
|
| 323 | - return $this->createResource( |
|
| 324 | - function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
| 325 | - $resource = @\fopen((string) $uri, 'r', false, $contextResource); |
|
| 326 | - $this->lastHeaders = $http_response_header ?? []; |
|
| 327 | - |
|
| 328 | - if (false === $resource) { |
|
| 329 | - throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); |
|
| 330 | - } |
|
| 331 | - |
|
| 332 | - if (isset($options['read_timeout'])) { |
|
| 333 | - $readTimeout = $options['read_timeout']; |
|
| 334 | - $sec = (int) $readTimeout; |
|
| 335 | - $usec = ($readTimeout - $sec) * 100000; |
|
| 336 | - \stream_set_timeout($resource, $sec, $usec); |
|
| 337 | - } |
|
| 338 | - |
|
| 339 | - return $resource; |
|
| 340 | - } |
|
| 341 | - ); |
|
| 342 | - } |
|
| 343 | - |
|
| 344 | - private function resolveHost(RequestInterface $request, array $options): UriInterface |
|
| 345 | - { |
|
| 346 | - $uri = $request->getUri(); |
|
| 347 | - |
|
| 348 | - if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { |
|
| 349 | - if ('v4' === $options['force_ip_resolve']) { |
|
| 350 | - $records = \dns_get_record($uri->getHost(), \DNS_A); |
|
| 351 | - if (false === $records || !isset($records[0]['ip'])) { |
|
| 352 | - throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); |
|
| 353 | - } |
|
| 354 | - |
|
| 355 | - return $uri->withHost($records[0]['ip']); |
|
| 356 | - } |
|
| 357 | - if ('v6' === $options['force_ip_resolve']) { |
|
| 358 | - $records = \dns_get_record($uri->getHost(), \DNS_AAAA); |
|
| 359 | - if (false === $records || !isset($records[0]['ipv6'])) { |
|
| 360 | - throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); |
|
| 361 | - } |
|
| 362 | - |
|
| 363 | - return $uri->withHost('['.$records[0]['ipv6'].']'); |
|
| 364 | - } |
|
| 365 | - } |
|
| 366 | - |
|
| 367 | - return $uri; |
|
| 368 | - } |
|
| 369 | - |
|
| 370 | - private function getDefaultContext(RequestInterface $request): array |
|
| 371 | - { |
|
| 372 | - $headers = ''; |
|
| 373 | - foreach ($request->getHeaders() as $name => $value) { |
|
| 374 | - foreach ($value as $val) { |
|
| 375 | - $headers .= "$name: $val\r\n"; |
|
| 376 | - } |
|
| 377 | - } |
|
| 378 | - |
|
| 379 | - $context = [ |
|
| 380 | - 'http' => [ |
|
| 381 | - 'method' => $request->getMethod(), |
|
| 382 | - 'header' => $headers, |
|
| 383 | - 'protocol_version' => $request->getProtocolVersion(), |
|
| 384 | - 'ignore_errors' => true, |
|
| 385 | - 'follow_location' => 0, |
|
| 386 | - ], |
|
| 387 | - 'ssl' => [ |
|
| 388 | - 'peer_name' => $request->getUri()->getHost(), |
|
| 389 | - ], |
|
| 390 | - ]; |
|
| 391 | - |
|
| 392 | - $body = (string) $request->getBody(); |
|
| 393 | - |
|
| 394 | - if ('' !== $body) { |
|
| 395 | - $context['http']['content'] = $body; |
|
| 396 | - // Prevent the HTTP handler from adding a Content-Type header. |
|
| 397 | - if (!$request->hasHeader('Content-Type')) { |
|
| 398 | - $context['http']['header'] .= "Content-Type:\r\n"; |
|
| 399 | - } |
|
| 400 | - } |
|
| 401 | - |
|
| 402 | - $context['http']['header'] = \rtrim($context['http']['header']); |
|
| 403 | - |
|
| 404 | - return $context; |
|
| 405 | - } |
|
| 406 | - |
|
| 407 | - /** |
|
| 408 | - * @param mixed $value as passed via Request transfer options. |
|
| 409 | - */ |
|
| 410 | - private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 411 | - { |
|
| 412 | - $uri = null; |
|
| 413 | - |
|
| 414 | - if (!\is_array($value)) { |
|
| 415 | - $uri = $value; |
|
| 416 | - } else { |
|
| 417 | - $scheme = $request->getUri()->getScheme(); |
|
| 418 | - if (isset($value[$scheme])) { |
|
| 419 | - if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { |
|
| 420 | - $uri = $value[$scheme]; |
|
| 421 | - } |
|
| 422 | - } |
|
| 423 | - } |
|
| 424 | - |
|
| 425 | - if (!$uri) { |
|
| 426 | - return; |
|
| 427 | - } |
|
| 428 | - |
|
| 429 | - $parsed = $this->parse_proxy($uri); |
|
| 430 | - $options['http']['proxy'] = $parsed['proxy']; |
|
| 431 | - |
|
| 432 | - if ($parsed['auth']) { |
|
| 433 | - if (!isset($options['http']['header'])) { |
|
| 434 | - $options['http']['header'] = []; |
|
| 435 | - } |
|
| 436 | - $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; |
|
| 437 | - } |
|
| 438 | - } |
|
| 439 | - |
|
| 440 | - /** |
|
| 441 | - * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. |
|
| 442 | - */ |
|
| 443 | - private function parse_proxy(string $url): array |
|
| 444 | - { |
|
| 445 | - $parsed = \parse_url($url); |
|
| 446 | - |
|
| 447 | - if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { |
|
| 448 | - if (isset($parsed['host']) && isset($parsed['port'])) { |
|
| 449 | - $auth = null; |
|
| 450 | - if (isset($parsed['user']) && isset($parsed['pass'])) { |
|
| 451 | - $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); |
|
| 452 | - } |
|
| 453 | - |
|
| 454 | - return [ |
|
| 455 | - 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", |
|
| 456 | - 'auth' => $auth ? "Basic {$auth}" : null, |
|
| 457 | - ]; |
|
| 458 | - } |
|
| 459 | - } |
|
| 460 | - |
|
| 461 | - // Return proxy as-is. |
|
| 462 | - return [ |
|
| 463 | - 'proxy' => $url, |
|
| 464 | - 'auth' => null, |
|
| 465 | - ]; |
|
| 466 | - } |
|
| 467 | - |
|
| 468 | - /** |
|
| 469 | - * @param mixed $value as passed via Request transfer options. |
|
| 470 | - */ |
|
| 471 | - private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 472 | - { |
|
| 473 | - if ($value > 0) { |
|
| 474 | - $options['http']['timeout'] = $value; |
|
| 475 | - } |
|
| 476 | - } |
|
| 477 | - |
|
| 478 | - /** |
|
| 479 | - * @param mixed $value as passed via Request transfer options. |
|
| 480 | - */ |
|
| 481 | - private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 482 | - { |
|
| 483 | - if ( |
|
| 484 | - $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT |
|
| 485 | - || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
|
| 486 | - || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT |
|
| 487 | - || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) |
|
| 488 | - ) { |
|
| 489 | - $options['http']['crypto_method'] = $value; |
|
| 490 | - |
|
| 491 | - return; |
|
| 492 | - } |
|
| 493 | - |
|
| 494 | - throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); |
|
| 495 | - } |
|
| 496 | - |
|
| 497 | - /** |
|
| 498 | - * @param mixed $value as passed via Request transfer options. |
|
| 499 | - */ |
|
| 500 | - private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 501 | - { |
|
| 502 | - if ($value === false) { |
|
| 503 | - $options['ssl']['verify_peer'] = false; |
|
| 504 | - $options['ssl']['verify_peer_name'] = false; |
|
| 505 | - |
|
| 506 | - return; |
|
| 507 | - } |
|
| 508 | - |
|
| 509 | - if (\is_string($value)) { |
|
| 510 | - $options['ssl']['cafile'] = $value; |
|
| 511 | - if (!\file_exists($value)) { |
|
| 512 | - throw new \RuntimeException("SSL CA bundle not found: $value"); |
|
| 513 | - } |
|
| 514 | - } elseif ($value !== true) { |
|
| 515 | - throw new \InvalidArgumentException('Invalid verify request option'); |
|
| 516 | - } |
|
| 517 | - |
|
| 518 | - $options['ssl']['verify_peer'] = true; |
|
| 519 | - $options['ssl']['verify_peer_name'] = true; |
|
| 520 | - $options['ssl']['allow_self_signed'] = false; |
|
| 521 | - } |
|
| 522 | - |
|
| 523 | - /** |
|
| 524 | - * @param mixed $value as passed via Request transfer options. |
|
| 525 | - */ |
|
| 526 | - private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 527 | - { |
|
| 528 | - if (\is_array($value)) { |
|
| 529 | - $options['ssl']['passphrase'] = $value[1]; |
|
| 530 | - $value = $value[0]; |
|
| 531 | - } |
|
| 532 | - |
|
| 533 | - if (!\file_exists($value)) { |
|
| 534 | - throw new \RuntimeException("SSL certificate not found: {$value}"); |
|
| 535 | - } |
|
| 536 | - |
|
| 537 | - $options['ssl']['local_cert'] = $value; |
|
| 538 | - } |
|
| 539 | - |
|
| 540 | - /** |
|
| 541 | - * @param mixed $value as passed via Request transfer options. |
|
| 542 | - */ |
|
| 543 | - private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 544 | - { |
|
| 545 | - self::addNotification( |
|
| 546 | - $params, |
|
| 547 | - static function ($code, $a, $b, $c, $transferred, $total) use ($value) { |
|
| 548 | - if ($code == \STREAM_NOTIFY_PROGRESS) { |
|
| 549 | - // The upload progress cannot be determined. Use 0 for cURL compatibility: |
|
| 550 | - // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
|
| 551 | - $value($total, $transferred, 0, 0); |
|
| 552 | - } |
|
| 553 | - } |
|
| 554 | - ); |
|
| 555 | - } |
|
| 556 | - |
|
| 557 | - /** |
|
| 558 | - * @param mixed $value as passed via Request transfer options. |
|
| 559 | - */ |
|
| 560 | - private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 561 | - { |
|
| 562 | - if ($value === false) { |
|
| 563 | - return; |
|
| 564 | - } |
|
| 565 | - |
|
| 566 | - static $map = [ |
|
| 567 | - \STREAM_NOTIFY_CONNECT => 'CONNECT', |
|
| 568 | - \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', |
|
| 569 | - \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', |
|
| 570 | - \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', |
|
| 571 | - \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', |
|
| 572 | - \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', |
|
| 573 | - \STREAM_NOTIFY_PROGRESS => 'PROGRESS', |
|
| 574 | - \STREAM_NOTIFY_FAILURE => 'FAILURE', |
|
| 575 | - \STREAM_NOTIFY_COMPLETED => 'COMPLETED', |
|
| 576 | - \STREAM_NOTIFY_RESOLVE => 'RESOLVE', |
|
| 577 | - ]; |
|
| 578 | - static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; |
|
| 579 | - |
|
| 580 | - $value = Utils::debugResource($value); |
|
| 581 | - $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); |
|
| 582 | - self::addNotification( |
|
| 583 | - $params, |
|
| 584 | - static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { |
|
| 585 | - \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
|
| 586 | - foreach (\array_filter($passed) as $i => $v) { |
|
| 587 | - \fwrite($value, $args[$i].': "'.$v.'" '); |
|
| 588 | - } |
|
| 589 | - \fwrite($value, "\n"); |
|
| 590 | - } |
|
| 591 | - ); |
|
| 592 | - } |
|
| 593 | - |
|
| 594 | - private static function addNotification(array &$params, callable $notify): void |
|
| 595 | - { |
|
| 596 | - // Wrap the existing function if needed. |
|
| 597 | - if (!isset($params['notification'])) { |
|
| 598 | - $params['notification'] = $notify; |
|
| 599 | - } else { |
|
| 600 | - $params['notification'] = self::callArray([ |
|
| 601 | - $params['notification'], |
|
| 602 | - $notify, |
|
| 603 | - ]); |
|
| 604 | - } |
|
| 605 | - } |
|
| 606 | - |
|
| 607 | - private static function callArray(array $functions): callable |
|
| 608 | - { |
|
| 609 | - return static function (...$args) use ($functions) { |
|
| 610 | - foreach ($functions as $fn) { |
|
| 611 | - $fn(...$args); |
|
| 612 | - } |
|
| 613 | - }; |
|
| 614 | - } |
|
| 25 | + /** |
|
| 26 | + * @var array |
|
| 27 | + */ |
|
| 28 | + private $lastHeaders = []; |
|
| 29 | + |
|
| 30 | + /** |
|
| 31 | + * Sends an HTTP request. |
|
| 32 | + * |
|
| 33 | + * @param RequestInterface $request Request to send. |
|
| 34 | + * @param array $options Request transfer options. |
|
| 35 | + */ |
|
| 36 | + public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 37 | + { |
|
| 38 | + // Sleep if there is a delay specified. |
|
| 39 | + if (isset($options['delay'])) { |
|
| 40 | + \usleep($options['delay'] * 1000); |
|
| 41 | + } |
|
| 42 | + |
|
| 43 | + $startTime = isset($options['on_stats']) ? Utils::currentTime() : null; |
|
| 44 | + |
|
| 45 | + try { |
|
| 46 | + // Does not support the expect header. |
|
| 47 | + $request = $request->withoutHeader('Expect'); |
|
| 48 | + |
|
| 49 | + // Append a content-length header if body size is zero to match |
|
| 50 | + // cURL's behavior. |
|
| 51 | + if (0 === $request->getBody()->getSize()) { |
|
| 52 | + $request = $request->withHeader('Content-Length', '0'); |
|
| 53 | + } |
|
| 54 | + |
|
| 55 | + return $this->createResponse( |
|
| 56 | + $request, |
|
| 57 | + $options, |
|
| 58 | + $this->createStream($request, $options), |
|
| 59 | + $startTime |
|
| 60 | + ); |
|
| 61 | + } catch (\InvalidArgumentException $e) { |
|
| 62 | + throw $e; |
|
| 63 | + } catch (\Exception $e) { |
|
| 64 | + // Determine if the error was a networking error. |
|
| 65 | + $message = $e->getMessage(); |
|
| 66 | + // This list can probably get more comprehensive. |
|
| 67 | + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed |
|
| 68 | + || false !== \strpos($message, 'Connection refused') |
|
| 69 | + || false !== \strpos($message, "couldn't connect to host") // error on HHVM |
|
| 70 | + || false !== \strpos($message, 'connection attempt failed') |
|
| 71 | + ) { |
|
| 72 | + $e = new ConnectException($e->getMessage(), $request, $e); |
|
| 73 | + } else { |
|
| 74 | + $e = RequestException::wrapException($request, $e); |
|
| 75 | + } |
|
| 76 | + $this->invokeStats($options, $request, $startTime, null, $e); |
|
| 77 | + |
|
| 78 | + return P\Create::rejectionFor($e); |
|
| 79 | + } |
|
| 80 | + } |
|
| 81 | + |
|
| 82 | + private function invokeStats( |
|
| 83 | + array $options, |
|
| 84 | + RequestInterface $request, |
|
| 85 | + ?float $startTime, |
|
| 86 | + ResponseInterface $response = null, |
|
| 87 | + \Throwable $error = null |
|
| 88 | + ): void { |
|
| 89 | + if (isset($options['on_stats'])) { |
|
| 90 | + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); |
|
| 91 | + ($options['on_stats'])($stats); |
|
| 92 | + } |
|
| 93 | + } |
|
| 94 | + |
|
| 95 | + /** |
|
| 96 | + * @param resource $stream |
|
| 97 | + */ |
|
| 98 | + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface |
|
| 99 | + { |
|
| 100 | + $hdrs = $this->lastHeaders; |
|
| 101 | + $this->lastHeaders = []; |
|
| 102 | + |
|
| 103 | + try { |
|
| 104 | + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); |
|
| 105 | + } catch (\Exception $e) { |
|
| 106 | + return P\Create::rejectionFor( |
|
| 107 | + new RequestException('An error was encountered while creating the response', $request, null, $e) |
|
| 108 | + ); |
|
| 109 | + } |
|
| 110 | + |
|
| 111 | + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); |
|
| 112 | + $stream = Psr7\Utils::streamFor($stream); |
|
| 113 | + $sink = $stream; |
|
| 114 | + |
|
| 115 | + if (\strcasecmp('HEAD', $request->getMethod())) { |
|
| 116 | + $sink = $this->createSink($stream, $options); |
|
| 117 | + } |
|
| 118 | + |
|
| 119 | + try { |
|
| 120 | + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); |
|
| 121 | + } catch (\Exception $e) { |
|
| 122 | + return P\Create::rejectionFor( |
|
| 123 | + new RequestException('An error was encountered while creating the response', $request, null, $e) |
|
| 124 | + ); |
|
| 125 | + } |
|
| 126 | + |
|
| 127 | + if (isset($options['on_headers'])) { |
|
| 128 | + try { |
|
| 129 | + $options['on_headers']($response); |
|
| 130 | + } catch (\Exception $e) { |
|
| 131 | + return P\Create::rejectionFor( |
|
| 132 | + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) |
|
| 133 | + ); |
|
| 134 | + } |
|
| 135 | + } |
|
| 136 | + |
|
| 137 | + // Do not drain when the request is a HEAD request because they have |
|
| 138 | + // no body. |
|
| 139 | + if ($sink !== $stream) { |
|
| 140 | + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); |
|
| 141 | + } |
|
| 142 | + |
|
| 143 | + $this->invokeStats($options, $request, $startTime, $response, null); |
|
| 144 | + |
|
| 145 | + return new FulfilledPromise($response); |
|
| 146 | + } |
|
| 147 | + |
|
| 148 | + private function createSink(StreamInterface $stream, array $options): StreamInterface |
|
| 149 | + { |
|
| 150 | + if (!empty($options['stream'])) { |
|
| 151 | + return $stream; |
|
| 152 | + } |
|
| 153 | + |
|
| 154 | + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); |
|
| 155 | + |
|
| 156 | + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); |
|
| 157 | + } |
|
| 158 | + |
|
| 159 | + /** |
|
| 160 | + * @param resource $stream |
|
| 161 | + */ |
|
| 162 | + private function checkDecode(array $options, array $headers, $stream): array |
|
| 163 | + { |
|
| 164 | + // Automatically decode responses when instructed. |
|
| 165 | + if (!empty($options['decode_content'])) { |
|
| 166 | + $normalizedKeys = Utils::normalizeHeaderKeys($headers); |
|
| 167 | + if (isset($normalizedKeys['content-encoding'])) { |
|
| 168 | + $encoding = $headers[$normalizedKeys['content-encoding']]; |
|
| 169 | + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { |
|
| 170 | + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); |
|
| 171 | + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; |
|
| 172 | + |
|
| 173 | + // Remove content-encoding header |
|
| 174 | + unset($headers[$normalizedKeys['content-encoding']]); |
|
| 175 | + |
|
| 176 | + // Fix content-length header |
|
| 177 | + if (isset($normalizedKeys['content-length'])) { |
|
| 178 | + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
|
| 179 | + $length = (int) $stream->getSize(); |
|
| 180 | + if ($length === 0) { |
|
| 181 | + unset($headers[$normalizedKeys['content-length']]); |
|
| 182 | + } else { |
|
| 183 | + $headers[$normalizedKeys['content-length']] = [$length]; |
|
| 184 | + } |
|
| 185 | + } |
|
| 186 | + } |
|
| 187 | + } |
|
| 188 | + } |
|
| 189 | + |
|
| 190 | + return [$stream, $headers]; |
|
| 191 | + } |
|
| 192 | + |
|
| 193 | + /** |
|
| 194 | + * Drains the source stream into the "sink" client option. |
|
| 195 | + * |
|
| 196 | + * @param string $contentLength Header specifying the amount of |
|
| 197 | + * data to read. |
|
| 198 | + * |
|
| 199 | + * @throws \RuntimeException when the sink option is invalid. |
|
| 200 | + */ |
|
| 201 | + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface |
|
| 202 | + { |
|
| 203 | + // If a content-length header is provided, then stop reading once |
|
| 204 | + // that number of bytes has been read. This can prevent infinitely |
|
| 205 | + // reading from a stream when dealing with servers that do not honor |
|
| 206 | + // Connection: Close headers. |
|
| 207 | + Psr7\Utils::copyToStream( |
|
| 208 | + $source, |
|
| 209 | + $sink, |
|
| 210 | + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 |
|
| 211 | + ); |
|
| 212 | + |
|
| 213 | + $sink->seek(0); |
|
| 214 | + $source->close(); |
|
| 215 | + |
|
| 216 | + return $sink; |
|
| 217 | + } |
|
| 218 | + |
|
| 219 | + /** |
|
| 220 | + * Create a resource and check to ensure it was created successfully |
|
| 221 | + * |
|
| 222 | + * @param callable $callback Callable that returns stream resource |
|
| 223 | + * |
|
| 224 | + * @return resource |
|
| 225 | + * |
|
| 226 | + * @throws \RuntimeException on error |
|
| 227 | + */ |
|
| 228 | + private function createResource(callable $callback) |
|
| 229 | + { |
|
| 230 | + $errors = []; |
|
| 231 | + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { |
|
| 232 | + $errors[] = [ |
|
| 233 | + 'message' => $msg, |
|
| 234 | + 'file' => $file, |
|
| 235 | + 'line' => $line, |
|
| 236 | + ]; |
|
| 237 | + |
|
| 238 | + return true; |
|
| 239 | + }); |
|
| 240 | + |
|
| 241 | + try { |
|
| 242 | + $resource = $callback(); |
|
| 243 | + } finally { |
|
| 244 | + \restore_error_handler(); |
|
| 245 | + } |
|
| 246 | + |
|
| 247 | + if (!$resource) { |
|
| 248 | + $message = 'Error creating resource: '; |
|
| 249 | + foreach ($errors as $err) { |
|
| 250 | + foreach ($err as $key => $value) { |
|
| 251 | + $message .= "[$key] $value".\PHP_EOL; |
|
| 252 | + } |
|
| 253 | + } |
|
| 254 | + throw new \RuntimeException(\trim($message)); |
|
| 255 | + } |
|
| 256 | + |
|
| 257 | + return $resource; |
|
| 258 | + } |
|
| 259 | + |
|
| 260 | + /** |
|
| 261 | + * @return resource |
|
| 262 | + */ |
|
| 263 | + private function createStream(RequestInterface $request, array $options) |
|
| 264 | + { |
|
| 265 | + static $methods; |
|
| 266 | + if (!$methods) { |
|
| 267 | + $methods = \array_flip(\get_class_methods(__CLASS__)); |
|
| 268 | + } |
|
| 269 | + |
|
| 270 | + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { |
|
| 271 | + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); |
|
| 272 | + } |
|
| 273 | + |
|
| 274 | + // HTTP/1.1 streams using the PHP stream wrapper require a |
|
| 275 | + // Connection: close header |
|
| 276 | + if ($request->getProtocolVersion() == '1.1' |
|
| 277 | + && !$request->hasHeader('Connection') |
|
| 278 | + ) { |
|
| 279 | + $request = $request->withHeader('Connection', 'close'); |
|
| 280 | + } |
|
| 281 | + |
|
| 282 | + // Ensure SSL is verified by default |
|
| 283 | + if (!isset($options['verify'])) { |
|
| 284 | + $options['verify'] = true; |
|
| 285 | + } |
|
| 286 | + |
|
| 287 | + $params = []; |
|
| 288 | + $context = $this->getDefaultContext($request); |
|
| 289 | + |
|
| 290 | + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { |
|
| 291 | + throw new \InvalidArgumentException('on_headers must be callable'); |
|
| 292 | + } |
|
| 293 | + |
|
| 294 | + if (!empty($options)) { |
|
| 295 | + foreach ($options as $key => $value) { |
|
| 296 | + $method = "add_{$key}"; |
|
| 297 | + if (isset($methods[$method])) { |
|
| 298 | + $this->{$method}($request, $context, $value, $params); |
|
| 299 | + } |
|
| 300 | + } |
|
| 301 | + } |
|
| 302 | + |
|
| 303 | + if (isset($options['stream_context'])) { |
|
| 304 | + if (!\is_array($options['stream_context'])) { |
|
| 305 | + throw new \InvalidArgumentException('stream_context must be an array'); |
|
| 306 | + } |
|
| 307 | + $context = \array_replace_recursive($context, $options['stream_context']); |
|
| 308 | + } |
|
| 309 | + |
|
| 310 | + // Microsoft NTLM authentication only supported with curl handler |
|
| 311 | + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { |
|
| 312 | + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); |
|
| 313 | + } |
|
| 314 | + |
|
| 315 | + $uri = $this->resolveHost($request, $options); |
|
| 316 | + |
|
| 317 | + $contextResource = $this->createResource( |
|
| 318 | + static function () use ($context, $params) { |
|
| 319 | + return \stream_context_create($context, $params); |
|
| 320 | + } |
|
| 321 | + ); |
|
| 322 | + |
|
| 323 | + return $this->createResource( |
|
| 324 | + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
| 325 | + $resource = @\fopen((string) $uri, 'r', false, $contextResource); |
|
| 326 | + $this->lastHeaders = $http_response_header ?? []; |
|
| 327 | + |
|
| 328 | + if (false === $resource) { |
|
| 329 | + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); |
|
| 330 | + } |
|
| 331 | + |
|
| 332 | + if (isset($options['read_timeout'])) { |
|
| 333 | + $readTimeout = $options['read_timeout']; |
|
| 334 | + $sec = (int) $readTimeout; |
|
| 335 | + $usec = ($readTimeout - $sec) * 100000; |
|
| 336 | + \stream_set_timeout($resource, $sec, $usec); |
|
| 337 | + } |
|
| 338 | + |
|
| 339 | + return $resource; |
|
| 340 | + } |
|
| 341 | + ); |
|
| 342 | + } |
|
| 343 | + |
|
| 344 | + private function resolveHost(RequestInterface $request, array $options): UriInterface |
|
| 345 | + { |
|
| 346 | + $uri = $request->getUri(); |
|
| 347 | + |
|
| 348 | + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { |
|
| 349 | + if ('v4' === $options['force_ip_resolve']) { |
|
| 350 | + $records = \dns_get_record($uri->getHost(), \DNS_A); |
|
| 351 | + if (false === $records || !isset($records[0]['ip'])) { |
|
| 352 | + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); |
|
| 353 | + } |
|
| 354 | + |
|
| 355 | + return $uri->withHost($records[0]['ip']); |
|
| 356 | + } |
|
| 357 | + if ('v6' === $options['force_ip_resolve']) { |
|
| 358 | + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); |
|
| 359 | + if (false === $records || !isset($records[0]['ipv6'])) { |
|
| 360 | + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); |
|
| 361 | + } |
|
| 362 | + |
|
| 363 | + return $uri->withHost('['.$records[0]['ipv6'].']'); |
|
| 364 | + } |
|
| 365 | + } |
|
| 366 | + |
|
| 367 | + return $uri; |
|
| 368 | + } |
|
| 369 | + |
|
| 370 | + private function getDefaultContext(RequestInterface $request): array |
|
| 371 | + { |
|
| 372 | + $headers = ''; |
|
| 373 | + foreach ($request->getHeaders() as $name => $value) { |
|
| 374 | + foreach ($value as $val) { |
|
| 375 | + $headers .= "$name: $val\r\n"; |
|
| 376 | + } |
|
| 377 | + } |
|
| 378 | + |
|
| 379 | + $context = [ |
|
| 380 | + 'http' => [ |
|
| 381 | + 'method' => $request->getMethod(), |
|
| 382 | + 'header' => $headers, |
|
| 383 | + 'protocol_version' => $request->getProtocolVersion(), |
|
| 384 | + 'ignore_errors' => true, |
|
| 385 | + 'follow_location' => 0, |
|
| 386 | + ], |
|
| 387 | + 'ssl' => [ |
|
| 388 | + 'peer_name' => $request->getUri()->getHost(), |
|
| 389 | + ], |
|
| 390 | + ]; |
|
| 391 | + |
|
| 392 | + $body = (string) $request->getBody(); |
|
| 393 | + |
|
| 394 | + if ('' !== $body) { |
|
| 395 | + $context['http']['content'] = $body; |
|
| 396 | + // Prevent the HTTP handler from adding a Content-Type header. |
|
| 397 | + if (!$request->hasHeader('Content-Type')) { |
|
| 398 | + $context['http']['header'] .= "Content-Type:\r\n"; |
|
| 399 | + } |
|
| 400 | + } |
|
| 401 | + |
|
| 402 | + $context['http']['header'] = \rtrim($context['http']['header']); |
|
| 403 | + |
|
| 404 | + return $context; |
|
| 405 | + } |
|
| 406 | + |
|
| 407 | + /** |
|
| 408 | + * @param mixed $value as passed via Request transfer options. |
|
| 409 | + */ |
|
| 410 | + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 411 | + { |
|
| 412 | + $uri = null; |
|
| 413 | + |
|
| 414 | + if (!\is_array($value)) { |
|
| 415 | + $uri = $value; |
|
| 416 | + } else { |
|
| 417 | + $scheme = $request->getUri()->getScheme(); |
|
| 418 | + if (isset($value[$scheme])) { |
|
| 419 | + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { |
|
| 420 | + $uri = $value[$scheme]; |
|
| 421 | + } |
|
| 422 | + } |
|
| 423 | + } |
|
| 424 | + |
|
| 425 | + if (!$uri) { |
|
| 426 | + return; |
|
| 427 | + } |
|
| 428 | + |
|
| 429 | + $parsed = $this->parse_proxy($uri); |
|
| 430 | + $options['http']['proxy'] = $parsed['proxy']; |
|
| 431 | + |
|
| 432 | + if ($parsed['auth']) { |
|
| 433 | + if (!isset($options['http']['header'])) { |
|
| 434 | + $options['http']['header'] = []; |
|
| 435 | + } |
|
| 436 | + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; |
|
| 437 | + } |
|
| 438 | + } |
|
| 439 | + |
|
| 440 | + /** |
|
| 441 | + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. |
|
| 442 | + */ |
|
| 443 | + private function parse_proxy(string $url): array |
|
| 444 | + { |
|
| 445 | + $parsed = \parse_url($url); |
|
| 446 | + |
|
| 447 | + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { |
|
| 448 | + if (isset($parsed['host']) && isset($parsed['port'])) { |
|
| 449 | + $auth = null; |
|
| 450 | + if (isset($parsed['user']) && isset($parsed['pass'])) { |
|
| 451 | + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); |
|
| 452 | + } |
|
| 453 | + |
|
| 454 | + return [ |
|
| 455 | + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", |
|
| 456 | + 'auth' => $auth ? "Basic {$auth}" : null, |
|
| 457 | + ]; |
|
| 458 | + } |
|
| 459 | + } |
|
| 460 | + |
|
| 461 | + // Return proxy as-is. |
|
| 462 | + return [ |
|
| 463 | + 'proxy' => $url, |
|
| 464 | + 'auth' => null, |
|
| 465 | + ]; |
|
| 466 | + } |
|
| 467 | + |
|
| 468 | + /** |
|
| 469 | + * @param mixed $value as passed via Request transfer options. |
|
| 470 | + */ |
|
| 471 | + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 472 | + { |
|
| 473 | + if ($value > 0) { |
|
| 474 | + $options['http']['timeout'] = $value; |
|
| 475 | + } |
|
| 476 | + } |
|
| 477 | + |
|
| 478 | + /** |
|
| 479 | + * @param mixed $value as passed via Request transfer options. |
|
| 480 | + */ |
|
| 481 | + private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 482 | + { |
|
| 483 | + if ( |
|
| 484 | + $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT |
|
| 485 | + || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
|
| 486 | + || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT |
|
| 487 | + || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) |
|
| 488 | + ) { |
|
| 489 | + $options['http']['crypto_method'] = $value; |
|
| 490 | + |
|
| 491 | + return; |
|
| 492 | + } |
|
| 493 | + |
|
| 494 | + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); |
|
| 495 | + } |
|
| 496 | + |
|
| 497 | + /** |
|
| 498 | + * @param mixed $value as passed via Request transfer options. |
|
| 499 | + */ |
|
| 500 | + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 501 | + { |
|
| 502 | + if ($value === false) { |
|
| 503 | + $options['ssl']['verify_peer'] = false; |
|
| 504 | + $options['ssl']['verify_peer_name'] = false; |
|
| 505 | + |
|
| 506 | + return; |
|
| 507 | + } |
|
| 508 | + |
|
| 509 | + if (\is_string($value)) { |
|
| 510 | + $options['ssl']['cafile'] = $value; |
|
| 511 | + if (!\file_exists($value)) { |
|
| 512 | + throw new \RuntimeException("SSL CA bundle not found: $value"); |
|
| 513 | + } |
|
| 514 | + } elseif ($value !== true) { |
|
| 515 | + throw new \InvalidArgumentException('Invalid verify request option'); |
|
| 516 | + } |
|
| 517 | + |
|
| 518 | + $options['ssl']['verify_peer'] = true; |
|
| 519 | + $options['ssl']['verify_peer_name'] = true; |
|
| 520 | + $options['ssl']['allow_self_signed'] = false; |
|
| 521 | + } |
|
| 522 | + |
|
| 523 | + /** |
|
| 524 | + * @param mixed $value as passed via Request transfer options. |
|
| 525 | + */ |
|
| 526 | + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 527 | + { |
|
| 528 | + if (\is_array($value)) { |
|
| 529 | + $options['ssl']['passphrase'] = $value[1]; |
|
| 530 | + $value = $value[0]; |
|
| 531 | + } |
|
| 532 | + |
|
| 533 | + if (!\file_exists($value)) { |
|
| 534 | + throw new \RuntimeException("SSL certificate not found: {$value}"); |
|
| 535 | + } |
|
| 536 | + |
|
| 537 | + $options['ssl']['local_cert'] = $value; |
|
| 538 | + } |
|
| 539 | + |
|
| 540 | + /** |
|
| 541 | + * @param mixed $value as passed via Request transfer options. |
|
| 542 | + */ |
|
| 543 | + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 544 | + { |
|
| 545 | + self::addNotification( |
|
| 546 | + $params, |
|
| 547 | + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { |
|
| 548 | + if ($code == \STREAM_NOTIFY_PROGRESS) { |
|
| 549 | + // The upload progress cannot be determined. Use 0 for cURL compatibility: |
|
| 550 | + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
|
| 551 | + $value($total, $transferred, 0, 0); |
|
| 552 | + } |
|
| 553 | + } |
|
| 554 | + ); |
|
| 555 | + } |
|
| 556 | + |
|
| 557 | + /** |
|
| 558 | + * @param mixed $value as passed via Request transfer options. |
|
| 559 | + */ |
|
| 560 | + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void |
|
| 561 | + { |
|
| 562 | + if ($value === false) { |
|
| 563 | + return; |
|
| 564 | + } |
|
| 565 | + |
|
| 566 | + static $map = [ |
|
| 567 | + \STREAM_NOTIFY_CONNECT => 'CONNECT', |
|
| 568 | + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', |
|
| 569 | + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', |
|
| 570 | + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', |
|
| 571 | + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', |
|
| 572 | + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', |
|
| 573 | + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', |
|
| 574 | + \STREAM_NOTIFY_FAILURE => 'FAILURE', |
|
| 575 | + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', |
|
| 576 | + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', |
|
| 577 | + ]; |
|
| 578 | + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; |
|
| 579 | + |
|
| 580 | + $value = Utils::debugResource($value); |
|
| 581 | + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); |
|
| 582 | + self::addNotification( |
|
| 583 | + $params, |
|
| 584 | + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { |
|
| 585 | + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
|
| 586 | + foreach (\array_filter($passed) as $i => $v) { |
|
| 587 | + \fwrite($value, $args[$i].': "'.$v.'" '); |
|
| 588 | + } |
|
| 589 | + \fwrite($value, "\n"); |
|
| 590 | + } |
|
| 591 | + ); |
|
| 592 | + } |
|
| 593 | + |
|
| 594 | + private static function addNotification(array &$params, callable $notify): void |
|
| 595 | + { |
|
| 596 | + // Wrap the existing function if needed. |
|
| 597 | + if (!isset($params['notification'])) { |
|
| 598 | + $params['notification'] = $notify; |
|
| 599 | + } else { |
|
| 600 | + $params['notification'] = self::callArray([ |
|
| 601 | + $params['notification'], |
|
| 602 | + $notify, |
|
| 603 | + ]); |
|
| 604 | + } |
|
| 605 | + } |
|
| 606 | + |
|
| 607 | + private static function callArray(array $functions): callable |
|
| 608 | + { |
|
| 609 | + return static function (...$args) use ($functions) { |
|
| 610 | + foreach ($functions as $fn) { |
|
| 611 | + $fn(...$args); |
|
| 612 | + } |
|
| 613 | + }; |
|
| 614 | + } |
|
| 615 | 615 | } |
@@ -176,7 +176,7 @@ discard block |
||
| 176 | 176 | // Fix content-length header |
| 177 | 177 | if (isset($normalizedKeys['content-length'])) { |
| 178 | 178 | $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; |
| 179 | - $length = (int) $stream->getSize(); |
|
| 179 | + $length = (int)$stream->getSize(); |
|
| 180 | 180 | if ($length === 0) { |
| 181 | 181 | unset($headers[$normalizedKeys['content-length']]); |
| 182 | 182 | } else { |
@@ -207,7 +207,7 @@ discard block |
||
| 207 | 207 | Psr7\Utils::copyToStream( |
| 208 | 208 | $source, |
| 209 | 209 | $sink, |
| 210 | - (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 |
|
| 210 | + (\strlen($contentLength) > 0 && (int)$contentLength > 0) ? (int)$contentLength : -1 |
|
| 211 | 211 | ); |
| 212 | 212 | |
| 213 | 213 | $sink->seek(0); |
@@ -228,7 +228,7 @@ discard block |
||
| 228 | 228 | private function createResource(callable $callback) |
| 229 | 229 | { |
| 230 | 230 | $errors = []; |
| 231 | - \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { |
|
| 231 | + \set_error_handler(static function($_, $msg, $file, $line) use (&$errors): bool { |
|
| 232 | 232 | $errors[] = [ |
| 233 | 233 | 'message' => $msg, |
| 234 | 234 | 'file' => $file, |
@@ -315,14 +315,14 @@ discard block |
||
| 315 | 315 | $uri = $this->resolveHost($request, $options); |
| 316 | 316 | |
| 317 | 317 | $contextResource = $this->createResource( |
| 318 | - static function () use ($context, $params) { |
|
| 318 | + static function() use ($context, $params) { |
|
| 319 | 319 | return \stream_context_create($context, $params); |
| 320 | 320 | } |
| 321 | 321 | ); |
| 322 | 322 | |
| 323 | 323 | return $this->createResource( |
| 324 | - function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
| 325 | - $resource = @\fopen((string) $uri, 'r', false, $contextResource); |
|
| 324 | + function() use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { |
|
| 325 | + $resource = @\fopen((string)$uri, 'r', false, $contextResource); |
|
| 326 | 326 | $this->lastHeaders = $http_response_header ?? []; |
| 327 | 327 | |
| 328 | 328 | if (false === $resource) { |
@@ -331,7 +331,7 @@ discard block |
||
| 331 | 331 | |
| 332 | 332 | if (isset($options['read_timeout'])) { |
| 333 | 333 | $readTimeout = $options['read_timeout']; |
| 334 | - $sec = (int) $readTimeout; |
|
| 334 | + $sec = (int)$readTimeout; |
|
| 335 | 335 | $usec = ($readTimeout - $sec) * 100000; |
| 336 | 336 | \stream_set_timeout($resource, $sec, $usec); |
| 337 | 337 | } |
@@ -389,7 +389,7 @@ discard block |
||
| 389 | 389 | ], |
| 390 | 390 | ]; |
| 391 | 391 | |
| 392 | - $body = (string) $request->getBody(); |
|
| 392 | + $body = (string)$request->getBody(); |
|
| 393 | 393 | |
| 394 | 394 | if ('' !== $body) { |
| 395 | 395 | $context['http']['content'] = $body; |
@@ -544,7 +544,7 @@ discard block |
||
| 544 | 544 | { |
| 545 | 545 | self::addNotification( |
| 546 | 546 | $params, |
| 547 | - static function ($code, $a, $b, $c, $transferred, $total) use ($value) { |
|
| 547 | + static function($code, $a, $b, $c, $transferred, $total) use ($value) { |
|
| 548 | 548 | if ($code == \STREAM_NOTIFY_PROGRESS) { |
| 549 | 549 | // The upload progress cannot be determined. Use 0 for cURL compatibility: |
| 550 | 550 | // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html |
@@ -581,7 +581,7 @@ discard block |
||
| 581 | 581 | $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); |
| 582 | 582 | self::addNotification( |
| 583 | 583 | $params, |
| 584 | - static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { |
|
| 584 | + static function(int $code, ...$passed) use ($ident, $value, $map, $args): void { |
|
| 585 | 585 | \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); |
| 586 | 586 | foreach (\array_filter($passed) as $i => $v) { |
| 587 | 587 | \fwrite($value, $args[$i].': "'.$v.'" '); |
@@ -606,7 +606,7 @@ discard block |
||
| 606 | 606 | |
| 607 | 607 | private static function callArray(array $functions): callable |
| 608 | 608 | { |
| 609 | - return static function (...$args) use ($functions) { |
|
| 609 | + return static function(...$args) use ($functions) { |
|
| 610 | 610 | foreach ($functions as $fn) { |
| 611 | 611 | $fn(...$args); |
| 612 | 612 | } |
@@ -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 | */ |
@@ -19,249 +19,249 @@ |
||
| 19 | 19 | */ |
| 20 | 20 | class CurlMultiHandler |
| 21 | 21 | { |
| 22 | - /** |
|
| 23 | - * @var CurlFactoryInterface |
|
| 24 | - */ |
|
| 25 | - private $factory; |
|
| 26 | - |
|
| 27 | - /** |
|
| 28 | - * @var int |
|
| 29 | - */ |
|
| 30 | - private $selectTimeout; |
|
| 31 | - |
|
| 32 | - /** |
|
| 33 | - * @var int Will be higher than 0 when `curl_multi_exec` is still running. |
|
| 34 | - */ |
|
| 35 | - private $active = 0; |
|
| 36 | - |
|
| 37 | - /** |
|
| 38 | - * @var array Request entry handles, indexed by handle id in `addRequest`. |
|
| 39 | - * |
|
| 40 | - * @see CurlMultiHandler::addRequest |
|
| 41 | - */ |
|
| 42 | - private $handles = []; |
|
| 43 | - |
|
| 44 | - /** |
|
| 45 | - * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`. |
|
| 46 | - * |
|
| 47 | - * @see CurlMultiHandler::addRequest |
|
| 48 | - */ |
|
| 49 | - private $delays = []; |
|
| 50 | - |
|
| 51 | - /** |
|
| 52 | - * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() |
|
| 53 | - */ |
|
| 54 | - private $options = []; |
|
| 55 | - |
|
| 56 | - /** @var resource|\CurlMultiHandle */ |
|
| 57 | - private $_mh; |
|
| 58 | - |
|
| 59 | - /** |
|
| 60 | - * This handler accepts the following options: |
|
| 61 | - * |
|
| 62 | - * - handle_factory: An optional factory used to create curl handles |
|
| 63 | - * - select_timeout: Optional timeout (in seconds) to block before timing |
|
| 64 | - * out while selecting curl handles. Defaults to 1 second. |
|
| 65 | - * - options: An associative array of CURLMOPT_* options and |
|
| 66 | - * corresponding values for curl_multi_setopt() |
|
| 67 | - */ |
|
| 68 | - public function __construct(array $options = []) |
|
| 69 | - { |
|
| 70 | - $this->factory = $options['handle_factory'] ?? new CurlFactory(50); |
|
| 71 | - |
|
| 72 | - if (isset($options['select_timeout'])) { |
|
| 73 | - $this->selectTimeout = $options['select_timeout']; |
|
| 74 | - } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
|
| 75 | - @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); |
|
| 76 | - $this->selectTimeout = (int) $selectTimeout; |
|
| 77 | - } else { |
|
| 78 | - $this->selectTimeout = 1; |
|
| 79 | - } |
|
| 80 | - |
|
| 81 | - $this->options = $options['options'] ?? []; |
|
| 82 | - |
|
| 83 | - // unsetting the property forces the first access to go through |
|
| 84 | - // __get(). |
|
| 85 | - unset($this->_mh); |
|
| 86 | - } |
|
| 87 | - |
|
| 88 | - /** |
|
| 89 | - * @param string $name |
|
| 90 | - * |
|
| 91 | - * @return resource|\CurlMultiHandle |
|
| 92 | - * |
|
| 93 | - * @throws \BadMethodCallException when another field as `_mh` will be gotten |
|
| 94 | - * @throws \RuntimeException when curl can not initialize a multi handle |
|
| 95 | - */ |
|
| 96 | - public function __get($name) |
|
| 97 | - { |
|
| 98 | - if ($name !== '_mh') { |
|
| 99 | - throw new \BadMethodCallException("Can not get other property as '_mh'."); |
|
| 100 | - } |
|
| 101 | - |
|
| 102 | - $multiHandle = \curl_multi_init(); |
|
| 103 | - |
|
| 104 | - if (false === $multiHandle) { |
|
| 105 | - throw new \RuntimeException('Can not initialize curl multi handle.'); |
|
| 106 | - } |
|
| 107 | - |
|
| 108 | - $this->_mh = $multiHandle; |
|
| 109 | - |
|
| 110 | - foreach ($this->options as $option => $value) { |
|
| 111 | - // A warning is raised in case of a wrong option. |
|
| 112 | - curl_multi_setopt($this->_mh, $option, $value); |
|
| 113 | - } |
|
| 114 | - |
|
| 115 | - return $this->_mh; |
|
| 116 | - } |
|
| 117 | - |
|
| 118 | - public function __destruct() |
|
| 119 | - { |
|
| 120 | - if (isset($this->_mh)) { |
|
| 121 | - \curl_multi_close($this->_mh); |
|
| 122 | - unset($this->_mh); |
|
| 123 | - } |
|
| 124 | - } |
|
| 125 | - |
|
| 126 | - public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 127 | - { |
|
| 128 | - $easy = $this->factory->create($request, $options); |
|
| 129 | - $id = (int) $easy->handle; |
|
| 130 | - |
|
| 131 | - $promise = new Promise( |
|
| 132 | - [$this, 'execute'], |
|
| 133 | - function () use ($id) { |
|
| 134 | - return $this->cancel($id); |
|
| 135 | - } |
|
| 136 | - ); |
|
| 137 | - |
|
| 138 | - $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
|
| 139 | - |
|
| 140 | - return $promise; |
|
| 141 | - } |
|
| 142 | - |
|
| 143 | - /** |
|
| 144 | - * Ticks the curl event loop. |
|
| 145 | - */ |
|
| 146 | - public function tick(): void |
|
| 147 | - { |
|
| 148 | - // Add any delayed handles if needed. |
|
| 149 | - if ($this->delays) { |
|
| 150 | - $currentTime = Utils::currentTime(); |
|
| 151 | - foreach ($this->delays as $id => $delay) { |
|
| 152 | - if ($currentTime >= $delay) { |
|
| 153 | - unset($this->delays[$id]); |
|
| 154 | - \curl_multi_add_handle( |
|
| 155 | - $this->_mh, |
|
| 156 | - $this->handles[$id]['easy']->handle |
|
| 157 | - ); |
|
| 158 | - } |
|
| 159 | - } |
|
| 160 | - } |
|
| 161 | - |
|
| 162 | - // Step through the task queue which may add additional requests. |
|
| 163 | - P\Utils::queue()->run(); |
|
| 164 | - |
|
| 165 | - if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { |
|
| 166 | - // Perform a usleep if a select returns -1. |
|
| 167 | - // See: https://bugs.php.net/bug.php?id=61141 |
|
| 168 | - \usleep(250); |
|
| 169 | - } |
|
| 170 | - |
|
| 171 | - while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { |
|
| 172 | - } |
|
| 173 | - |
|
| 174 | - $this->processMessages(); |
|
| 175 | - } |
|
| 176 | - |
|
| 177 | - /** |
|
| 178 | - * Runs until all outstanding connections have completed. |
|
| 179 | - */ |
|
| 180 | - public function execute(): void |
|
| 181 | - { |
|
| 182 | - $queue = P\Utils::queue(); |
|
| 183 | - |
|
| 184 | - while ($this->handles || !$queue->isEmpty()) { |
|
| 185 | - // If there are no transfers, then sleep for the next delay |
|
| 186 | - if (!$this->active && $this->delays) { |
|
| 187 | - \usleep($this->timeToNext()); |
|
| 188 | - } |
|
| 189 | - $this->tick(); |
|
| 190 | - } |
|
| 191 | - } |
|
| 192 | - |
|
| 193 | - private function addRequest(array $entry): void |
|
| 194 | - { |
|
| 195 | - $easy = $entry['easy']; |
|
| 196 | - $id = (int) $easy->handle; |
|
| 197 | - $this->handles[$id] = $entry; |
|
| 198 | - if (empty($easy->options['delay'])) { |
|
| 199 | - \curl_multi_add_handle($this->_mh, $easy->handle); |
|
| 200 | - } else { |
|
| 201 | - $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); |
|
| 202 | - } |
|
| 203 | - } |
|
| 204 | - |
|
| 205 | - /** |
|
| 206 | - * Cancels a handle from sending and removes references to it. |
|
| 207 | - * |
|
| 208 | - * @param int $id Handle ID to cancel and remove. |
|
| 209 | - * |
|
| 210 | - * @return bool True on success, false on failure. |
|
| 211 | - */ |
|
| 212 | - private function cancel($id): bool |
|
| 213 | - { |
|
| 214 | - if (!is_int($id)) { |
|
| 215 | - 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__); |
|
| 216 | - } |
|
| 217 | - |
|
| 218 | - // Cannot cancel if it has been processed. |
|
| 219 | - if (!isset($this->handles[$id])) { |
|
| 220 | - return false; |
|
| 221 | - } |
|
| 222 | - |
|
| 223 | - $handle = $this->handles[$id]['easy']->handle; |
|
| 224 | - unset($this->delays[$id], $this->handles[$id]); |
|
| 225 | - \curl_multi_remove_handle($this->_mh, $handle); |
|
| 226 | - \curl_close($handle); |
|
| 227 | - |
|
| 228 | - return true; |
|
| 229 | - } |
|
| 230 | - |
|
| 231 | - private function processMessages(): void |
|
| 232 | - { |
|
| 233 | - while ($done = \curl_multi_info_read($this->_mh)) { |
|
| 234 | - if ($done['msg'] !== \CURLMSG_DONE) { |
|
| 235 | - // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
|
| 236 | - continue; |
|
| 237 | - } |
|
| 238 | - $id = (int) $done['handle']; |
|
| 239 | - \curl_multi_remove_handle($this->_mh, $done['handle']); |
|
| 240 | - |
|
| 241 | - if (!isset($this->handles[$id])) { |
|
| 242 | - // Probably was cancelled. |
|
| 243 | - continue; |
|
| 244 | - } |
|
| 245 | - |
|
| 246 | - $entry = $this->handles[$id]; |
|
| 247 | - unset($this->handles[$id], $this->delays[$id]); |
|
| 248 | - $entry['easy']->errno = $done['result']; |
|
| 249 | - $entry['deferred']->resolve( |
|
| 250 | - CurlFactory::finish($this, $entry['easy'], $this->factory) |
|
| 251 | - ); |
|
| 252 | - } |
|
| 253 | - } |
|
| 254 | - |
|
| 255 | - private function timeToNext(): int |
|
| 256 | - { |
|
| 257 | - $currentTime = Utils::currentTime(); |
|
| 258 | - $nextTime = \PHP_INT_MAX; |
|
| 259 | - foreach ($this->delays as $time) { |
|
| 260 | - if ($time < $nextTime) { |
|
| 261 | - $nextTime = $time; |
|
| 262 | - } |
|
| 263 | - } |
|
| 264 | - |
|
| 265 | - return ((int) \max(0, $nextTime - $currentTime)) * 1000000; |
|
| 266 | - } |
|
| 22 | + /** |
|
| 23 | + * @var CurlFactoryInterface |
|
| 24 | + */ |
|
| 25 | + private $factory; |
|
| 26 | + |
|
| 27 | + /** |
|
| 28 | + * @var int |
|
| 29 | + */ |
|
| 30 | + private $selectTimeout; |
|
| 31 | + |
|
| 32 | + /** |
|
| 33 | + * @var int Will be higher than 0 when `curl_multi_exec` is still running. |
|
| 34 | + */ |
|
| 35 | + private $active = 0; |
|
| 36 | + |
|
| 37 | + /** |
|
| 38 | + * @var array Request entry handles, indexed by handle id in `addRequest`. |
|
| 39 | + * |
|
| 40 | + * @see CurlMultiHandler::addRequest |
|
| 41 | + */ |
|
| 42 | + private $handles = []; |
|
| 43 | + |
|
| 44 | + /** |
|
| 45 | + * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`. |
|
| 46 | + * |
|
| 47 | + * @see CurlMultiHandler::addRequest |
|
| 48 | + */ |
|
| 49 | + private $delays = []; |
|
| 50 | + |
|
| 51 | + /** |
|
| 52 | + * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() |
|
| 53 | + */ |
|
| 54 | + private $options = []; |
|
| 55 | + |
|
| 56 | + /** @var resource|\CurlMultiHandle */ |
|
| 57 | + private $_mh; |
|
| 58 | + |
|
| 59 | + /** |
|
| 60 | + * This handler accepts the following options: |
|
| 61 | + * |
|
| 62 | + * - handle_factory: An optional factory used to create curl handles |
|
| 63 | + * - select_timeout: Optional timeout (in seconds) to block before timing |
|
| 64 | + * out while selecting curl handles. Defaults to 1 second. |
|
| 65 | + * - options: An associative array of CURLMOPT_* options and |
|
| 66 | + * corresponding values for curl_multi_setopt() |
|
| 67 | + */ |
|
| 68 | + public function __construct(array $options = []) |
|
| 69 | + { |
|
| 70 | + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); |
|
| 71 | + |
|
| 72 | + if (isset($options['select_timeout'])) { |
|
| 73 | + $this->selectTimeout = $options['select_timeout']; |
|
| 74 | + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
|
| 75 | + @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); |
|
| 76 | + $this->selectTimeout = (int) $selectTimeout; |
|
| 77 | + } else { |
|
| 78 | + $this->selectTimeout = 1; |
|
| 79 | + } |
|
| 80 | + |
|
| 81 | + $this->options = $options['options'] ?? []; |
|
| 82 | + |
|
| 83 | + // unsetting the property forces the first access to go through |
|
| 84 | + // __get(). |
|
| 85 | + unset($this->_mh); |
|
| 86 | + } |
|
| 87 | + |
|
| 88 | + /** |
|
| 89 | + * @param string $name |
|
| 90 | + * |
|
| 91 | + * @return resource|\CurlMultiHandle |
|
| 92 | + * |
|
| 93 | + * @throws \BadMethodCallException when another field as `_mh` will be gotten |
|
| 94 | + * @throws \RuntimeException when curl can not initialize a multi handle |
|
| 95 | + */ |
|
| 96 | + public function __get($name) |
|
| 97 | + { |
|
| 98 | + if ($name !== '_mh') { |
|
| 99 | + throw new \BadMethodCallException("Can not get other property as '_mh'."); |
|
| 100 | + } |
|
| 101 | + |
|
| 102 | + $multiHandle = \curl_multi_init(); |
|
| 103 | + |
|
| 104 | + if (false === $multiHandle) { |
|
| 105 | + throw new \RuntimeException('Can not initialize curl multi handle.'); |
|
| 106 | + } |
|
| 107 | + |
|
| 108 | + $this->_mh = $multiHandle; |
|
| 109 | + |
|
| 110 | + foreach ($this->options as $option => $value) { |
|
| 111 | + // A warning is raised in case of a wrong option. |
|
| 112 | + curl_multi_setopt($this->_mh, $option, $value); |
|
| 113 | + } |
|
| 114 | + |
|
| 115 | + return $this->_mh; |
|
| 116 | + } |
|
| 117 | + |
|
| 118 | + public function __destruct() |
|
| 119 | + { |
|
| 120 | + if (isset($this->_mh)) { |
|
| 121 | + \curl_multi_close($this->_mh); |
|
| 122 | + unset($this->_mh); |
|
| 123 | + } |
|
| 124 | + } |
|
| 125 | + |
|
| 126 | + public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 127 | + { |
|
| 128 | + $easy = $this->factory->create($request, $options); |
|
| 129 | + $id = (int) $easy->handle; |
|
| 130 | + |
|
| 131 | + $promise = new Promise( |
|
| 132 | + [$this, 'execute'], |
|
| 133 | + function () use ($id) { |
|
| 134 | + return $this->cancel($id); |
|
| 135 | + } |
|
| 136 | + ); |
|
| 137 | + |
|
| 138 | + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); |
|
| 139 | + |
|
| 140 | + return $promise; |
|
| 141 | + } |
|
| 142 | + |
|
| 143 | + /** |
|
| 144 | + * Ticks the curl event loop. |
|
| 145 | + */ |
|
| 146 | + public function tick(): void |
|
| 147 | + { |
|
| 148 | + // Add any delayed handles if needed. |
|
| 149 | + if ($this->delays) { |
|
| 150 | + $currentTime = Utils::currentTime(); |
|
| 151 | + foreach ($this->delays as $id => $delay) { |
|
| 152 | + if ($currentTime >= $delay) { |
|
| 153 | + unset($this->delays[$id]); |
|
| 154 | + \curl_multi_add_handle( |
|
| 155 | + $this->_mh, |
|
| 156 | + $this->handles[$id]['easy']->handle |
|
| 157 | + ); |
|
| 158 | + } |
|
| 159 | + } |
|
| 160 | + } |
|
| 161 | + |
|
| 162 | + // Step through the task queue which may add additional requests. |
|
| 163 | + P\Utils::queue()->run(); |
|
| 164 | + |
|
| 165 | + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { |
|
| 166 | + // Perform a usleep if a select returns -1. |
|
| 167 | + // See: https://bugs.php.net/bug.php?id=61141 |
|
| 168 | + \usleep(250); |
|
| 169 | + } |
|
| 170 | + |
|
| 171 | + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { |
|
| 172 | + } |
|
| 173 | + |
|
| 174 | + $this->processMessages(); |
|
| 175 | + } |
|
| 176 | + |
|
| 177 | + /** |
|
| 178 | + * Runs until all outstanding connections have completed. |
|
| 179 | + */ |
|
| 180 | + public function execute(): void |
|
| 181 | + { |
|
| 182 | + $queue = P\Utils::queue(); |
|
| 183 | + |
|
| 184 | + while ($this->handles || !$queue->isEmpty()) { |
|
| 185 | + // If there are no transfers, then sleep for the next delay |
|
| 186 | + if (!$this->active && $this->delays) { |
|
| 187 | + \usleep($this->timeToNext()); |
|
| 188 | + } |
|
| 189 | + $this->tick(); |
|
| 190 | + } |
|
| 191 | + } |
|
| 192 | + |
|
| 193 | + private function addRequest(array $entry): void |
|
| 194 | + { |
|
| 195 | + $easy = $entry['easy']; |
|
| 196 | + $id = (int) $easy->handle; |
|
| 197 | + $this->handles[$id] = $entry; |
|
| 198 | + if (empty($easy->options['delay'])) { |
|
| 199 | + \curl_multi_add_handle($this->_mh, $easy->handle); |
|
| 200 | + } else { |
|
| 201 | + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); |
|
| 202 | + } |
|
| 203 | + } |
|
| 204 | + |
|
| 205 | + /** |
|
| 206 | + * Cancels a handle from sending and removes references to it. |
|
| 207 | + * |
|
| 208 | + * @param int $id Handle ID to cancel and remove. |
|
| 209 | + * |
|
| 210 | + * @return bool True on success, false on failure. |
|
| 211 | + */ |
|
| 212 | + private function cancel($id): bool |
|
| 213 | + { |
|
| 214 | + if (!is_int($id)) { |
|
| 215 | + 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__); |
|
| 216 | + } |
|
| 217 | + |
|
| 218 | + // Cannot cancel if it has been processed. |
|
| 219 | + if (!isset($this->handles[$id])) { |
|
| 220 | + return false; |
|
| 221 | + } |
|
| 222 | + |
|
| 223 | + $handle = $this->handles[$id]['easy']->handle; |
|
| 224 | + unset($this->delays[$id], $this->handles[$id]); |
|
| 225 | + \curl_multi_remove_handle($this->_mh, $handle); |
|
| 226 | + \curl_close($handle); |
|
| 227 | + |
|
| 228 | + return true; |
|
| 229 | + } |
|
| 230 | + |
|
| 231 | + private function processMessages(): void |
|
| 232 | + { |
|
| 233 | + while ($done = \curl_multi_info_read($this->_mh)) { |
|
| 234 | + if ($done['msg'] !== \CURLMSG_DONE) { |
|
| 235 | + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
|
| 236 | + continue; |
|
| 237 | + } |
|
| 238 | + $id = (int) $done['handle']; |
|
| 239 | + \curl_multi_remove_handle($this->_mh, $done['handle']); |
|
| 240 | + |
|
| 241 | + if (!isset($this->handles[$id])) { |
|
| 242 | + // Probably was cancelled. |
|
| 243 | + continue; |
|
| 244 | + } |
|
| 245 | + |
|
| 246 | + $entry = $this->handles[$id]; |
|
| 247 | + unset($this->handles[$id], $this->delays[$id]); |
|
| 248 | + $entry['easy']->errno = $done['result']; |
|
| 249 | + $entry['deferred']->resolve( |
|
| 250 | + CurlFactory::finish($this, $entry['easy'], $this->factory) |
|
| 251 | + ); |
|
| 252 | + } |
|
| 253 | + } |
|
| 254 | + |
|
| 255 | + private function timeToNext(): int |
|
| 256 | + { |
|
| 257 | + $currentTime = Utils::currentTime(); |
|
| 258 | + $nextTime = \PHP_INT_MAX; |
|
| 259 | + foreach ($this->delays as $time) { |
|
| 260 | + if ($time < $nextTime) { |
|
| 261 | + $nextTime = $time; |
|
| 262 | + } |
|
| 263 | + } |
|
| 264 | + |
|
| 265 | + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; |
|
| 266 | + } |
|
| 267 | 267 | } |
@@ -73,7 +73,7 @@ discard block |
||
| 73 | 73 | $this->selectTimeout = $options['select_timeout']; |
| 74 | 74 | } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { |
| 75 | 75 | @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); |
| 76 | - $this->selectTimeout = (int) $selectTimeout; |
|
| 76 | + $this->selectTimeout = (int)$selectTimeout; |
|
| 77 | 77 | } else { |
| 78 | 78 | $this->selectTimeout = 1; |
| 79 | 79 | } |
@@ -126,11 +126,11 @@ discard block |
||
| 126 | 126 | public function __invoke(RequestInterface $request, array $options): PromiseInterface |
| 127 | 127 | { |
| 128 | 128 | $easy = $this->factory->create($request, $options); |
| 129 | - $id = (int) $easy->handle; |
|
| 129 | + $id = (int)$easy->handle; |
|
| 130 | 130 | |
| 131 | 131 | $promise = new Promise( |
| 132 | 132 | [$this, 'execute'], |
| 133 | - function () use ($id) { |
|
| 133 | + function() use ($id) { |
|
| 134 | 134 | return $this->cancel($id); |
| 135 | 135 | } |
| 136 | 136 | ); |
@@ -193,7 +193,7 @@ discard block |
||
| 193 | 193 | private function addRequest(array $entry): void |
| 194 | 194 | { |
| 195 | 195 | $easy = $entry['easy']; |
| 196 | - $id = (int) $easy->handle; |
|
| 196 | + $id = (int)$easy->handle; |
|
| 197 | 197 | $this->handles[$id] = $entry; |
| 198 | 198 | if (empty($easy->options['delay'])) { |
| 199 | 199 | \curl_multi_add_handle($this->_mh, $easy->handle); |
@@ -235,7 +235,7 @@ discard block |
||
| 235 | 235 | // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 |
| 236 | 236 | continue; |
| 237 | 237 | } |
| 238 | - $id = (int) $done['handle']; |
|
| 238 | + $id = (int)$done['handle']; |
|
| 239 | 239 | \curl_multi_remove_handle($this->_mh, $done['handle']); |
| 240 | 240 | |
| 241 | 241 | if (!isset($this->handles[$id])) { |
@@ -262,6 +262,6 @@ discard block |
||
| 262 | 262 | } |
| 263 | 263 | } |
| 264 | 264 | |
| 265 | - return ((int) \max(0, $nextTime - $currentTime)) * 1000000; |
|
| 265 | + return ((int)\max(0, $nextTime - $currentTime)) * 1000000; |
|
| 266 | 266 | } |
| 267 | 267 | } |
@@ -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 | */ |
@@ -9,34 +9,34 @@ |
||
| 9 | 9 | */ |
| 10 | 10 | final class HeaderProcessor |
| 11 | 11 | { |
| 12 | - /** |
|
| 13 | - * Returns the HTTP version, status code, reason phrase, and headers. |
|
| 14 | - * |
|
| 15 | - * @param string[] $headers |
|
| 16 | - * |
|
| 17 | - * @return array{0:string, 1:int, 2:?string, 3:array} |
|
| 18 | - * |
|
| 19 | - * @throws \RuntimeException |
|
| 20 | - */ |
|
| 21 | - public static function parseHeaders(array $headers): array |
|
| 22 | - { |
|
| 23 | - if ($headers === []) { |
|
| 24 | - throw new \RuntimeException('Expected a non-empty array of header data'); |
|
| 25 | - } |
|
| 26 | - |
|
| 27 | - $parts = \explode(' ', \array_shift($headers), 3); |
|
| 28 | - $version = \explode('/', $parts[0])[1] ?? null; |
|
| 29 | - |
|
| 30 | - if ($version === null) { |
|
| 31 | - throw new \RuntimeException('HTTP version missing from header data'); |
|
| 32 | - } |
|
| 33 | - |
|
| 34 | - $status = $parts[1] ?? null; |
|
| 35 | - |
|
| 36 | - if ($status === null) { |
|
| 37 | - throw new \RuntimeException('HTTP status code missing from header data'); |
|
| 38 | - } |
|
| 39 | - |
|
| 40 | - return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
| 41 | - } |
|
| 12 | + /** |
|
| 13 | + * Returns the HTTP version, status code, reason phrase, and headers. |
|
| 14 | + * |
|
| 15 | + * @param string[] $headers |
|
| 16 | + * |
|
| 17 | + * @return array{0:string, 1:int, 2:?string, 3:array} |
|
| 18 | + * |
|
| 19 | + * @throws \RuntimeException |
|
| 20 | + */ |
|
| 21 | + public static function parseHeaders(array $headers): array |
|
| 22 | + { |
|
| 23 | + if ($headers === []) { |
|
| 24 | + throw new \RuntimeException('Expected a non-empty array of header data'); |
|
| 25 | + } |
|
| 26 | + |
|
| 27 | + $parts = \explode(' ', \array_shift($headers), 3); |
|
| 28 | + $version = \explode('/', $parts[0])[1] ?? null; |
|
| 29 | + |
|
| 30 | + if ($version === null) { |
|
| 31 | + throw new \RuntimeException('HTTP version missing from header data'); |
|
| 32 | + } |
|
| 33 | + |
|
| 34 | + $status = $parts[1] ?? null; |
|
| 35 | + |
|
| 36 | + if ($status === null) { |
|
| 37 | + throw new \RuntimeException('HTTP status code missing from header data'); |
|
| 38 | + } |
|
| 39 | + |
|
| 40 | + return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
| 41 | + } |
|
| 42 | 42 | } |
@@ -37,6 +37,6 @@ |
||
| 37 | 37 | throw new \RuntimeException('HTTP status code missing from header data'); |
| 38 | 38 | } |
| 39 | 39 | |
| 40 | - return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
| 40 | + return [$version, (int)$status, $parts[2] ?? null, Utils::headersFromLines($headers)]; |
|
| 41 | 41 | } |
| 42 | 42 | } |
@@ -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 | * |
@@ -19,194 +19,194 @@ |
||
| 19 | 19 | */ |
| 20 | 20 | class MockHandler implements \Countable |
| 21 | 21 | { |
| 22 | - /** |
|
| 23 | - * @var array |
|
| 24 | - */ |
|
| 25 | - private $queue = []; |
|
| 26 | - |
|
| 27 | - /** |
|
| 28 | - * @var RequestInterface|null |
|
| 29 | - */ |
|
| 30 | - private $lastRequest; |
|
| 31 | - |
|
| 32 | - /** |
|
| 33 | - * @var array |
|
| 34 | - */ |
|
| 35 | - private $lastOptions = []; |
|
| 36 | - |
|
| 37 | - /** |
|
| 38 | - * @var callable|null |
|
| 39 | - */ |
|
| 40 | - private $onFulfilled; |
|
| 41 | - |
|
| 42 | - /** |
|
| 43 | - * @var callable|null |
|
| 44 | - */ |
|
| 45 | - private $onRejected; |
|
| 46 | - |
|
| 47 | - /** |
|
| 48 | - * Creates a new MockHandler that uses the default handler stack list of |
|
| 49 | - * middlewares. |
|
| 50 | - * |
|
| 51 | - * @param array|null $queue Array of responses, callables, or exceptions. |
|
| 52 | - * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. |
|
| 53 | - * @param callable|null $onRejected Callback to invoke when the return value is rejected. |
|
| 54 | - */ |
|
| 55 | - public static function createWithMiddleware(array $queue = null, callable $onFulfilled = null, callable $onRejected = null): HandlerStack |
|
| 56 | - { |
|
| 57 | - return HandlerStack::create(new self($queue, $onFulfilled, $onRejected)); |
|
| 58 | - } |
|
| 59 | - |
|
| 60 | - /** |
|
| 61 | - * The passed in value must be an array of |
|
| 62 | - * {@see \OCA\FullTextSearch_Elasticsearch\Vendor\Psr\Http\Message\ResponseInterface} objects, Exceptions, |
|
| 63 | - * callables, or Promises. |
|
| 64 | - * |
|
| 65 | - * @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array. |
|
| 66 | - * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. |
|
| 67 | - * @param callable|null $onRejected Callback to invoke when the return value is rejected. |
|
| 68 | - */ |
|
| 69 | - public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) |
|
| 70 | - { |
|
| 71 | - $this->onFulfilled = $onFulfilled; |
|
| 72 | - $this->onRejected = $onRejected; |
|
| 73 | - |
|
| 74 | - if ($queue) { |
|
| 75 | - // array_values included for BC |
|
| 76 | - $this->append(...array_values($queue)); |
|
| 77 | - } |
|
| 78 | - } |
|
| 79 | - |
|
| 80 | - public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 81 | - { |
|
| 82 | - if (!$this->queue) { |
|
| 83 | - throw new \OutOfBoundsException('Mock queue is empty'); |
|
| 84 | - } |
|
| 85 | - |
|
| 86 | - if (isset($options['delay']) && \is_numeric($options['delay'])) { |
|
| 87 | - \usleep((int) $options['delay'] * 1000); |
|
| 88 | - } |
|
| 89 | - |
|
| 90 | - $this->lastRequest = $request; |
|
| 91 | - $this->lastOptions = $options; |
|
| 92 | - $response = \array_shift($this->queue); |
|
| 93 | - |
|
| 94 | - if (isset($options['on_headers'])) { |
|
| 95 | - if (!\is_callable($options['on_headers'])) { |
|
| 96 | - throw new \InvalidArgumentException('on_headers must be callable'); |
|
| 97 | - } |
|
| 98 | - try { |
|
| 99 | - $options['on_headers']($response); |
|
| 100 | - } catch (\Exception $e) { |
|
| 101 | - $msg = 'An error was encountered during the on_headers event'; |
|
| 102 | - $response = new RequestException($msg, $request, $response, $e); |
|
| 103 | - } |
|
| 104 | - } |
|
| 105 | - |
|
| 106 | - if (\is_callable($response)) { |
|
| 107 | - $response = $response($request, $options); |
|
| 108 | - } |
|
| 109 | - |
|
| 110 | - $response = $response instanceof \Throwable |
|
| 111 | - ? P\Create::rejectionFor($response) |
|
| 112 | - : P\Create::promiseFor($response); |
|
| 113 | - |
|
| 114 | - return $response->then( |
|
| 115 | - function (?ResponseInterface $value) use ($request, $options) { |
|
| 116 | - $this->invokeStats($request, $options, $value); |
|
| 117 | - if ($this->onFulfilled) { |
|
| 118 | - ($this->onFulfilled)($value); |
|
| 119 | - } |
|
| 120 | - |
|
| 121 | - if ($value !== null && isset($options['sink'])) { |
|
| 122 | - $contents = (string) $value->getBody(); |
|
| 123 | - $sink = $options['sink']; |
|
| 124 | - |
|
| 125 | - if (\is_resource($sink)) { |
|
| 126 | - \fwrite($sink, $contents); |
|
| 127 | - } elseif (\is_string($sink)) { |
|
| 128 | - \file_put_contents($sink, $contents); |
|
| 129 | - } elseif ($sink instanceof StreamInterface) { |
|
| 130 | - $sink->write($contents); |
|
| 131 | - } |
|
| 132 | - } |
|
| 133 | - |
|
| 134 | - return $value; |
|
| 135 | - }, |
|
| 136 | - function ($reason) use ($request, $options) { |
|
| 137 | - $this->invokeStats($request, $options, null, $reason); |
|
| 138 | - if ($this->onRejected) { |
|
| 139 | - ($this->onRejected)($reason); |
|
| 140 | - } |
|
| 141 | - |
|
| 142 | - return P\Create::rejectionFor($reason); |
|
| 143 | - } |
|
| 144 | - ); |
|
| 145 | - } |
|
| 146 | - |
|
| 147 | - /** |
|
| 148 | - * Adds one or more variadic requests, exceptions, callables, or promises |
|
| 149 | - * to the queue. |
|
| 150 | - * |
|
| 151 | - * @param mixed ...$values |
|
| 152 | - */ |
|
| 153 | - public function append(...$values): void |
|
| 154 | - { |
|
| 155 | - foreach ($values as $value) { |
|
| 156 | - if ($value instanceof ResponseInterface |
|
| 157 | - || $value instanceof \Throwable |
|
| 158 | - || $value instanceof PromiseInterface |
|
| 159 | - || \is_callable($value) |
|
| 160 | - ) { |
|
| 161 | - $this->queue[] = $value; |
|
| 162 | - } else { |
|
| 163 | - throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value)); |
|
| 164 | - } |
|
| 165 | - } |
|
| 166 | - } |
|
| 167 | - |
|
| 168 | - /** |
|
| 169 | - * Get the last received request. |
|
| 170 | - */ |
|
| 171 | - public function getLastRequest(): ?RequestInterface |
|
| 172 | - { |
|
| 173 | - return $this->lastRequest; |
|
| 174 | - } |
|
| 175 | - |
|
| 176 | - /** |
|
| 177 | - * Get the last received request options. |
|
| 178 | - */ |
|
| 179 | - public function getLastOptions(): array |
|
| 180 | - { |
|
| 181 | - return $this->lastOptions; |
|
| 182 | - } |
|
| 183 | - |
|
| 184 | - /** |
|
| 185 | - * Returns the number of remaining items in the queue. |
|
| 186 | - */ |
|
| 187 | - public function count(): int |
|
| 188 | - { |
|
| 189 | - return \count($this->queue); |
|
| 190 | - } |
|
| 191 | - |
|
| 192 | - public function reset(): void |
|
| 193 | - { |
|
| 194 | - $this->queue = []; |
|
| 195 | - } |
|
| 196 | - |
|
| 197 | - /** |
|
| 198 | - * @param mixed $reason Promise or reason. |
|
| 199 | - */ |
|
| 200 | - private function invokeStats( |
|
| 201 | - RequestInterface $request, |
|
| 202 | - array $options, |
|
| 203 | - ResponseInterface $response = null, |
|
| 204 | - $reason = null |
|
| 205 | - ): void { |
|
| 206 | - if (isset($options['on_stats'])) { |
|
| 207 | - $transferTime = $options['transfer_time'] ?? 0; |
|
| 208 | - $stats = new TransferStats($request, $response, $transferTime, $reason); |
|
| 209 | - ($options['on_stats'])($stats); |
|
| 210 | - } |
|
| 211 | - } |
|
| 22 | + /** |
|
| 23 | + * @var array |
|
| 24 | + */ |
|
| 25 | + private $queue = []; |
|
| 26 | + |
|
| 27 | + /** |
|
| 28 | + * @var RequestInterface|null |
|
| 29 | + */ |
|
| 30 | + private $lastRequest; |
|
| 31 | + |
|
| 32 | + /** |
|
| 33 | + * @var array |
|
| 34 | + */ |
|
| 35 | + private $lastOptions = []; |
|
| 36 | + |
|
| 37 | + /** |
|
| 38 | + * @var callable|null |
|
| 39 | + */ |
|
| 40 | + private $onFulfilled; |
|
| 41 | + |
|
| 42 | + /** |
|
| 43 | + * @var callable|null |
|
| 44 | + */ |
|
| 45 | + private $onRejected; |
|
| 46 | + |
|
| 47 | + /** |
|
| 48 | + * Creates a new MockHandler that uses the default handler stack list of |
|
| 49 | + * middlewares. |
|
| 50 | + * |
|
| 51 | + * @param array|null $queue Array of responses, callables, or exceptions. |
|
| 52 | + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. |
|
| 53 | + * @param callable|null $onRejected Callback to invoke when the return value is rejected. |
|
| 54 | + */ |
|
| 55 | + public static function createWithMiddleware(array $queue = null, callable $onFulfilled = null, callable $onRejected = null): HandlerStack |
|
| 56 | + { |
|
| 57 | + return HandlerStack::create(new self($queue, $onFulfilled, $onRejected)); |
|
| 58 | + } |
|
| 59 | + |
|
| 60 | + /** |
|
| 61 | + * The passed in value must be an array of |
|
| 62 | + * {@see \OCA\FullTextSearch_Elasticsearch\Vendor\Psr\Http\Message\ResponseInterface} objects, Exceptions, |
|
| 63 | + * callables, or Promises. |
|
| 64 | + * |
|
| 65 | + * @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array. |
|
| 66 | + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. |
|
| 67 | + * @param callable|null $onRejected Callback to invoke when the return value is rejected. |
|
| 68 | + */ |
|
| 69 | + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) |
|
| 70 | + { |
|
| 71 | + $this->onFulfilled = $onFulfilled; |
|
| 72 | + $this->onRejected = $onRejected; |
|
| 73 | + |
|
| 74 | + if ($queue) { |
|
| 75 | + // array_values included for BC |
|
| 76 | + $this->append(...array_values($queue)); |
|
| 77 | + } |
|
| 78 | + } |
|
| 79 | + |
|
| 80 | + public function __invoke(RequestInterface $request, array $options): PromiseInterface |
|
| 81 | + { |
|
| 82 | + if (!$this->queue) { |
|
| 83 | + throw new \OutOfBoundsException('Mock queue is empty'); |
|
| 84 | + } |
|
| 85 | + |
|
| 86 | + if (isset($options['delay']) && \is_numeric($options['delay'])) { |
|
| 87 | + \usleep((int) $options['delay'] * 1000); |
|
| 88 | + } |
|
| 89 | + |
|
| 90 | + $this->lastRequest = $request; |
|
| 91 | + $this->lastOptions = $options; |
|
| 92 | + $response = \array_shift($this->queue); |
|
| 93 | + |
|
| 94 | + if (isset($options['on_headers'])) { |
|
| 95 | + if (!\is_callable($options['on_headers'])) { |
|
| 96 | + throw new \InvalidArgumentException('on_headers must be callable'); |
|
| 97 | + } |
|
| 98 | + try { |
|
| 99 | + $options['on_headers']($response); |
|
| 100 | + } catch (\Exception $e) { |
|
| 101 | + $msg = 'An error was encountered during the on_headers event'; |
|
| 102 | + $response = new RequestException($msg, $request, $response, $e); |
|
| 103 | + } |
|
| 104 | + } |
|
| 105 | + |
|
| 106 | + if (\is_callable($response)) { |
|
| 107 | + $response = $response($request, $options); |
|
| 108 | + } |
|
| 109 | + |
|
| 110 | + $response = $response instanceof \Throwable |
|
| 111 | + ? P\Create::rejectionFor($response) |
|
| 112 | + : P\Create::promiseFor($response); |
|
| 113 | + |
|
| 114 | + return $response->then( |
|
| 115 | + function (?ResponseInterface $value) use ($request, $options) { |
|
| 116 | + $this->invokeStats($request, $options, $value); |
|
| 117 | + if ($this->onFulfilled) { |
|
| 118 | + ($this->onFulfilled)($value); |
|
| 119 | + } |
|
| 120 | + |
|
| 121 | + if ($value !== null && isset($options['sink'])) { |
|
| 122 | + $contents = (string) $value->getBody(); |
|
| 123 | + $sink = $options['sink']; |
|
| 124 | + |
|
| 125 | + if (\is_resource($sink)) { |
|
| 126 | + \fwrite($sink, $contents); |
|
| 127 | + } elseif (\is_string($sink)) { |
|
| 128 | + \file_put_contents($sink, $contents); |
|
| 129 | + } elseif ($sink instanceof StreamInterface) { |
|
| 130 | + $sink->write($contents); |
|
| 131 | + } |
|
| 132 | + } |
|
| 133 | + |
|
| 134 | + return $value; |
|
| 135 | + }, |
|
| 136 | + function ($reason) use ($request, $options) { |
|
| 137 | + $this->invokeStats($request, $options, null, $reason); |
|
| 138 | + if ($this->onRejected) { |
|
| 139 | + ($this->onRejected)($reason); |
|
| 140 | + } |
|
| 141 | + |
|
| 142 | + return P\Create::rejectionFor($reason); |
|
| 143 | + } |
|
| 144 | + ); |
|
| 145 | + } |
|
| 146 | + |
|
| 147 | + /** |
|
| 148 | + * Adds one or more variadic requests, exceptions, callables, or promises |
|
| 149 | + * to the queue. |
|
| 150 | + * |
|
| 151 | + * @param mixed ...$values |
|
| 152 | + */ |
|
| 153 | + public function append(...$values): void |
|
| 154 | + { |
|
| 155 | + foreach ($values as $value) { |
|
| 156 | + if ($value instanceof ResponseInterface |
|
| 157 | + || $value instanceof \Throwable |
|
| 158 | + || $value instanceof PromiseInterface |
|
| 159 | + || \is_callable($value) |
|
| 160 | + ) { |
|
| 161 | + $this->queue[] = $value; |
|
| 162 | + } else { |
|
| 163 | + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value)); |
|
| 164 | + } |
|
| 165 | + } |
|
| 166 | + } |
|
| 167 | + |
|
| 168 | + /** |
|
| 169 | + * Get the last received request. |
|
| 170 | + */ |
|
| 171 | + public function getLastRequest(): ?RequestInterface |
|
| 172 | + { |
|
| 173 | + return $this->lastRequest; |
|
| 174 | + } |
|
| 175 | + |
|
| 176 | + /** |
|
| 177 | + * Get the last received request options. |
|
| 178 | + */ |
|
| 179 | + public function getLastOptions(): array |
|
| 180 | + { |
|
| 181 | + return $this->lastOptions; |
|
| 182 | + } |
|
| 183 | + |
|
| 184 | + /** |
|
| 185 | + * Returns the number of remaining items in the queue. |
|
| 186 | + */ |
|
| 187 | + public function count(): int |
|
| 188 | + { |
|
| 189 | + return \count($this->queue); |
|
| 190 | + } |
|
| 191 | + |
|
| 192 | + public function reset(): void |
|
| 193 | + { |
|
| 194 | + $this->queue = []; |
|
| 195 | + } |
|
| 196 | + |
|
| 197 | + /** |
|
| 198 | + * @param mixed $reason Promise or reason. |
|
| 199 | + */ |
|
| 200 | + private function invokeStats( |
|
| 201 | + RequestInterface $request, |
|
| 202 | + array $options, |
|
| 203 | + ResponseInterface $response = null, |
|
| 204 | + $reason = null |
|
| 205 | + ): void { |
|
| 206 | + if (isset($options['on_stats'])) { |
|
| 207 | + $transferTime = $options['transfer_time'] ?? 0; |
|
| 208 | + $stats = new TransferStats($request, $response, $transferTime, $reason); |
|
| 209 | + ($options['on_stats'])($stats); |
|
| 210 | + } |
|
| 211 | + } |
|
| 212 | 212 | } |
@@ -84,7 +84,7 @@ discard block |
||
| 84 | 84 | } |
| 85 | 85 | |
| 86 | 86 | if (isset($options['delay']) && \is_numeric($options['delay'])) { |
| 87 | - \usleep((int) $options['delay'] * 1000); |
|
| 87 | + \usleep((int)$options['delay'] * 1000); |
|
| 88 | 88 | } |
| 89 | 89 | |
| 90 | 90 | $this->lastRequest = $request; |
@@ -112,14 +112,14 @@ discard block |
||
| 112 | 112 | : P\Create::promiseFor($response); |
| 113 | 113 | |
| 114 | 114 | return $response->then( |
| 115 | - function (?ResponseInterface $value) use ($request, $options) { |
|
| 115 | + function(?ResponseInterface $value) use ($request, $options) { |
|
| 116 | 116 | $this->invokeStats($request, $options, $value); |
| 117 | 117 | if ($this->onFulfilled) { |
| 118 | 118 | ($this->onFulfilled)($value); |
| 119 | 119 | } |
| 120 | 120 | |
| 121 | 121 | if ($value !== null && isset($options['sink'])) { |
| 122 | - $contents = (string) $value->getBody(); |
|
| 122 | + $contents = (string)$value->getBody(); |
|
| 123 | 123 | $sink = $options['sink']; |
| 124 | 124 | |
| 125 | 125 | if (\is_resource($sink)) { |
@@ -133,7 +133,7 @@ discard block |
||
| 133 | 133 | |
| 134 | 134 | return $value; |
| 135 | 135 | }, |
| 136 | - function ($reason) use ($request, $options) { |
|
| 136 | + function($reason) use ($request, $options) { |
|
| 137 | 137 | $this->invokeStats($request, $options, null, $reason); |
| 138 | 138 | if ($this->onRejected) { |
| 139 | 139 | ($this->onRejected)($reason); |