4 use GuzzleHttp\Cookie\CookieJarInterface;
5 use GuzzleHttp\Exception\RequestException;
6 use GuzzleHttp\Promise\RejectedPromise;
8 use Psr\Http\Message\ResponseInterface;
9 use Psr\Log\LoggerInterface;
13 * Functions used to create and wrap handlers with handler middleware.
15 final class Middleware
18 * Middleware that adds cookies to requests.
20 * The options array must be set to a CookieJarInterface in order to use
21 * cookies. This is typically handled for you by a client.
23 * @return callable Returns a function that accepts the next handler.
25 public static function cookies()
27 return function (callable $handler) {
28 return function ($request, array $options) use ($handler) {
29 if (empty($options['cookies'])) {
30 return $handler($request, $options);
31 } elseif (!($options['cookies'] instanceof CookieJarInterface)) {
32 throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface');
34 $cookieJar = $options['cookies'];
35 $request = $cookieJar->withCookieHeader($request);
36 return $handler($request, $options)
38 function ($response) use ($cookieJar, $request) {
39 $cookieJar->extractCookies($request, $response);
48 * Middleware that throws exceptions for 4xx or 5xx responses when the
49 * "http_error" request option is set to true.
51 * @return callable Returns a function that accepts the next handler.
53 public static function httpErrors()
55 return function (callable $handler) {
56 return function ($request, array $options) use ($handler) {
57 if (empty($options['http_errors'])) {
58 return $handler($request, $options);
60 return $handler($request, $options)->then(
61 function (ResponseInterface $response) use ($request, $handler) {
62 $code = $response->getStatusCode();
66 throw RequestException::create($request, $response);
74 * Middleware that pushes history data to an ArrayAccess container.
76 * @param array $container Container to hold the history (by reference).
78 * @return callable Returns a function that accepts the next handler.
79 * @throws \InvalidArgumentException if container is not an array or ArrayAccess.
81 public static function history(&$container)
83 if (!is_array($container) && !$container instanceof \ArrayAccess) {
84 throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess');
87 return function (callable $handler) use (&$container) {
88 return function ($request, array $options) use ($handler, &$container) {
89 return $handler($request, $options)->then(
90 function ($value) use ($request, &$container, $options) {
92 'request' => $request,
99 function ($reason) use ($request, &$container, $options) {
101 'request' => $request,
104 'options' => $options
106 return \GuzzleHttp\Promise\rejection_for($reason);
114 * Middleware that invokes a callback before and after sending a request.
116 * The provided listener cannot modify or alter the response. It simply
117 * "taps" into the chain to be notified before returning the promise. The
118 * before listener accepts a request and options array, and the after
119 * listener accepts a request, options array, and response promise.
121 * @param callable $before Function to invoke before forwarding the request.
122 * @param callable $after Function invoked after forwarding.
124 * @return callable Returns a function that accepts the next handler.
126 public static function tap(callable $before = null, callable $after = null)
128 return function (callable $handler) use ($before, $after) {
129 return function ($request, array $options) use ($handler, $before, $after) {
131 $before($request, $options);
133 $response = $handler($request, $options);
135 $after($request, $options, $response);
143 * Middleware that handles request redirects.
145 * @return callable Returns a function that accepts the next handler.
147 public static function redirect()
149 return function (callable $handler) {
150 return new RedirectMiddleware($handler);
155 * Middleware that retries requests based on the boolean result of
156 * invoking the provided "decider" function.
158 * If no delay function is provided, a simple implementation of exponential
159 * backoff will be utilized.
161 * @param callable $decider Function that accepts the number of retries,
162 * a request, [response], and [exception] and
163 * returns true if the request is to be retried.
164 * @param callable $delay Function that accepts the number of retries and
165 * returns the number of milliseconds to delay.
167 * @return callable Returns a function that accepts the next handler.
169 public static function retry(callable $decider, callable $delay = null)
171 return function (callable $handler) use ($decider, $delay) {
172 return new RetryMiddleware($decider, $handler, $delay);
177 * Middleware that logs requests, responses, and errors using a message
180 * @param LoggerInterface $logger Logs messages.
181 * @param MessageFormatter $formatter Formatter used to create message strings.
182 * @param string $logLevel Level at which to log requests.
184 * @return callable Returns a function that accepts the next handler.
186 public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
188 return function (callable $handler) use ($logger, $formatter, $logLevel) {
189 return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) {
190 return $handler($request, $options)->then(
191 function ($response) use ($logger, $request, $formatter, $logLevel) {
192 $message = $formatter->format($request, $response);
193 $logger->log($logLevel, $message);
196 function ($reason) use ($logger, $request, $formatter) {
197 $response = $reason instanceof RequestException
198 ? $reason->getResponse()
200 $message = $formatter->format($request, $response, $reason);
201 $logger->notice($message);
202 return \GuzzleHttp\Promise\rejection_for($reason);
210 * This middleware adds a default content-type if possible, a default
211 * content-length or transfer-encoding header, and the expect header.
215 public static function prepareBody()
217 return function (callable $handler) {
218 return new PrepareBodyMiddleware($handler);
223 * Middleware that applies a map function to the request before passing to
226 * @param callable $fn Function that accepts a RequestInterface and returns
227 * a RequestInterface.
230 public static function mapRequest(callable $fn)
232 return function (callable $handler) use ($fn) {
233 return function ($request, array $options) use ($handler, $fn) {
234 return $handler($fn($request), $options);
240 * Middleware that applies a map function to the resolved promise's
243 * @param callable $fn Function that accepts a ResponseInterface and
244 * returns a ResponseInterface.
247 public static function mapResponse(callable $fn)
249 return function (callable $handler) use ($fn) {
250 return function ($request, array $options) use ($handler, $fn) {
251 return $handler($request, $options)->then($fn);