Middleware.php 9.7 KB

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