/vendor/guzzlehttp/guzzle/src/Middleware.php

https://gitlab.com/techniconline/kmc · PHP · 249 lines · 149 code · 11 blank · 89 comment · 5 complexity · 470cf1e6adcfa0f0798a60be348c859e MD5 · raw file

  1. <?php
  2. namespace GuzzleHttp;
  3. use GuzzleHttp\Cookie\CookieJarInterface;
  4. use GuzzleHttp\Exception\RequestException;
  5. use GuzzleHttp\Promise\RejectedPromise;
  6. use GuzzleHttp\Psr7;
  7. use Psr\Http\Message\ResponseInterface;
  8. use Psr\Log\LoggerInterface;
  9. use Psr\Log\LogLevel;
  10. /**
  11. * Functions used to create and wrap handlers with handler middleware.
  12. */
  13. final class Middleware
  14. {
  15. /**
  16. * Middleware that adds cookies to requests.
  17. *
  18. * The options array must be set to a CookieJarInterface in order to use
  19. * cookies. This is typically handled for you by a client.
  20. *
  21. * @return callable Returns a function that accepts the next handler.
  22. */
  23. public static function cookies()
  24. {
  25. return function (callable $handler) {
  26. return function ($request, array $options) use ($handler) {
  27. if (empty($options['cookies'])) {
  28. return $handler($request, $options);
  29. } elseif (!($options['cookies'] instanceof CookieJarInterface)) {
  30. throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface');
  31. }
  32. $cookieJar = $options['cookies'];
  33. $request = $cookieJar->withCookieHeader($request);
  34. return $handler($request, $options)
  35. ->then(function ($response) use ($cookieJar, $request) {
  36. $cookieJar->extractCookies($request, $response);
  37. return $response;
  38. }
  39. );
  40. };
  41. };
  42. }
  43. /**
  44. * Middleware that throws exceptions for 4xx or 5xx responses when the
  45. * "http_error" request option is set to true.
  46. *
  47. * @return callable Returns a function that accepts the next handler.
  48. */
  49. public static function httpErrors()
  50. {
  51. return function (callable $handler) {
  52. return function ($request, array $options) use ($handler) {
  53. if (empty($options['http_errors'])) {
  54. return $handler($request, $options);
  55. }
  56. return $handler($request, $options)->then(
  57. function (ResponseInterface $response) use ($request, $handler) {
  58. $code = $response->getStatusCode();
  59. if ($code < 400) {
  60. return $response;
  61. }
  62. throw RequestException::create($request, $response);
  63. }
  64. );
  65. };
  66. };
  67. }
  68. /**
  69. * Middleware that pushes history data to an ArrayAccess container.
  70. *
  71. * @param array $container Container to hold the history (by reference).
  72. *
  73. * @return callable Returns a function that accepts the next handler.
  74. */
  75. public static function history(array &$container)
  76. {
  77. return function (callable $handler) use (&$container) {
  78. return function ($request, array $options) use ($handler, &$container) {
  79. return $handler($request, $options)->then(
  80. function ($value) use ($request, &$container, $options) {
  81. $container[] = [
  82. 'request' => $request,
  83. 'response' => $value,
  84. 'error' => null,
  85. 'options' => $options
  86. ];
  87. return $value;
  88. },
  89. function ($reason) use ($request, &$container, $options) {
  90. $container[] = [
  91. 'request' => $request,
  92. 'response' => null,
  93. 'error' => $reason,
  94. 'options' => $options
  95. ];
  96. return new RejectedPromise($reason);
  97. }
  98. );
  99. };
  100. };
  101. }
  102. /**
  103. * Middleware that invokes a callback before and after sending a request.
  104. *
  105. * The provided listener cannot modify or alter the response. It simply
  106. * "taps" into the chain to be notified before returning the promise. The
  107. * before listener accepts a request and options array, and the after
  108. * listener accepts a request, options array, and response promise.
  109. *
  110. * @param callable $before Function to invoke before forwarding the request.
  111. * @param callable $after Function invoked after forwarding.
  112. *
  113. * @return callable Returns a function that accepts the next handler.
  114. */
  115. public static function tap(callable $before = null, callable $after = null)
  116. {
  117. return function (callable $handler) use ($before, $after) {
  118. return function ($request, array $options) use ($handler, $before, $after) {
  119. if ($before) {
  120. $before($request, $options);
  121. }
  122. $response = $handler($request, $options);
  123. if ($after) {
  124. $after($request, $options, $response);
  125. }
  126. return $response;
  127. };
  128. };
  129. }
  130. /**
  131. * Middleware that handles request redirects.
  132. *
  133. * @return callable Returns a function that accepts the next handler.
  134. */
  135. public static function redirect()
  136. {
  137. return function (callable $handler) {
  138. return new RedirectMiddleware($handler);
  139. };
  140. }
  141. /**
  142. * Middleware that retries requests based on the boolean result of
  143. * invoking the provided "decider" function.
  144. *
  145. * If no delay function is provided, a simple implementation of exponential
  146. * backoff will be utilized.
  147. *
  148. * @param callable $decider Function that accepts the number of retries,
  149. * a request, [response], and [exception] and
  150. * returns true if the request is to be retried.
  151. * @param callable $delay Function that accepts the number of retries and
  152. * returns the number of milliseconds to delay.
  153. *
  154. * @return callable Returns a function that accepts the next handler.
  155. */
  156. public static function retry(callable $decider, callable $delay = null)
  157. {
  158. return function (callable $handler) use ($decider, $delay) {
  159. return new RetryMiddleware($decider, $handler, $delay);
  160. };
  161. }
  162. /**
  163. * Middleware that logs requests, responses, and errors using a message
  164. * formatter.
  165. *
  166. * @param LoggerInterface $logger Logs messages.
  167. * @param MessageFormatter $formatter Formatter used to create message strings.
  168. * @param string $logLevel Level at which to log requests.
  169. *
  170. * @return callable Returns a function that accepts the next handler.
  171. */
  172. public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
  173. {
  174. return function (callable $handler) use ($logger, $formatter, $logLevel) {
  175. return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) {
  176. return $handler($request, $options)->then(
  177. function ($response) use ($logger, $request, $formatter, $logLevel) {
  178. $message = $formatter->format($request, $response);
  179. $logger->log($logLevel, $message);
  180. return $response;
  181. },
  182. function ($reason) use ($logger, $request, $formatter) {
  183. $response = $reason instanceof RequestException
  184. ? $reason->getResponse()
  185. : null;
  186. $message = $formatter->format($request, $response, $reason);
  187. $logger->notice($message);
  188. return \GuzzleHttp\Promise\rejection_for($reason);
  189. }
  190. );
  191. };
  192. };
  193. }
  194. /**
  195. * This middleware adds a default content-type if possible, a default
  196. * content-length or transfer-encoding header, and the expect header.
  197. *
  198. * @return callable
  199. */
  200. public static function prepareBody()
  201. {
  202. return function (callable $handler) {
  203. return new PrepareBodyMiddleware($handler);
  204. };
  205. }
  206. /**
  207. * Middleware that applies a map function to the request before passing to
  208. * the next handler.
  209. *
  210. * @param callable $fn Function that accepts a RequestInterface and returns
  211. * a RequestInterface.
  212. * @return callable
  213. */
  214. public static function mapRequest(callable $fn)
  215. {
  216. return function (callable $handler) use ($fn) {
  217. return function ($request, array $options) use ($handler, $fn) {
  218. return $handler($fn($request), $options);
  219. };
  220. };
  221. }
  222. /**
  223. * Middleware that applies a map function to the resolved promise's
  224. * response.
  225. *
  226. * @param callable $fn Function that accepts a ResponseInterface and
  227. * returns a ResponseInterface.
  228. * @return callable
  229. */
  230. public static function mapResponse(callable $fn)
  231. {
  232. return function (callable $handler) use ($fn) {
  233. return function ($request, array $options) use ($handler, $fn) {
  234. return $handler($request, $options)->then($fn);
  235. };
  236. };
  237. }
  238. }