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)
37 ->then(function ($response) use ($cookieJar, $request) {
38 $cookieJar->extractCookies($request, $response);
47 * Middleware that throws exceptions for 4xx or 5xx responses when the
48 * "http_error" request option is set to true.
50 * @return callable Returns a function that accepts the next handler.
52 public static function httpErrors()
54 return function (callable $handler) {
55 return function ($request, array $options) use ($handler) {
56 if (empty($options['http_errors'])) {
57 return $handler($request, $options);
59 return $handler($request, $options)->then(
60 function (ResponseInterface $response) use ($request, $handler) {
61 $code = $response->getStatusCode();
65 throw RequestException::create($request, $response);
73 * Middleware that pushes history data to an ArrayAccess container.
75 * @param array $container Container to hold the history (by reference).
77 * @return callable Returns a function that accepts the next handler.
78 * @throws \InvalidArgumentException if container is not an array or ArrayAccess.
80 public static function history(&$container)
82 if (!is_array($container) && !$container instanceof \ArrayAccess) {
83 throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess');
86 return function (callable $handler) use (&$container) {
87 return function ($request, array $options) use ($handler, &$container) {
88 return $handler($request, $options)->then(
89 function ($value) use ($request, &$container, $options) {
91 'request' => $request,
98 function ($reason) use ($request, &$container, $options) {
100 'request' => $request,
103 'options' => $options
105 return \GuzzleHttp\Promise\rejection_for($reason);
113 * Middleware that invokes a callback before and after sending a request.
115 * The provided listener cannot modify or alter the response. It simply
116 * "taps" into the chain to be notified before returning the promise. The
117 * before listener accepts a request and options array, and the after
118 * listener accepts a request, options array, and response promise.
120 * @param callable $before Function to invoke before forwarding the request.
121 * @param callable $after Function invoked after forwarding.
123 * @return callable Returns a function that accepts the next handler.
125 public static function tap(callable $before = null, callable $after = null)
127 return function (callable $handler) use ($before, $after) {
128 return function ($request, array $options) use ($handler, $before, $after) {
130 $before($request, $options);
132 $response = $handler($request, $options);
134 $after($request, $options, $response);
142 * Middleware that handles request redirects.
144 * @return callable Returns a function that accepts the next handler.
146 public static function redirect()
148 return function (callable $handler) {
149 return new RedirectMiddleware($handler);
154 * Middleware that retries requests based on the boolean result of
155 * invoking the provided "decider" function.
157 * If no delay function is provided, a simple implementation of exponential
158 * backoff will be utilized.
160 * @param callable $decider Function that accepts the number of retries,
161 * a request, [response], and [exception] and
162 * returns true if the request is to be retried.
163 * @param callable $delay Function that accepts the number of retries and
164 * returns the number of milliseconds to delay.
166 * @return callable Returns a function that accepts the next handler.
168 public static function retry(callable $decider, callable $delay = null)
170 return function (callable $handler) use ($decider, $delay) {
171 return new RetryMiddleware($decider, $handler, $delay);
176 * Middleware that logs requests, responses, and errors using a message
179 * @param LoggerInterface $logger Logs messages.
180 * @param MessageFormatter $formatter Formatter used to create message strings.
181 * @param string $logLevel Level at which to log requests.
183 * @return callable Returns a function that accepts the next handler.
185 public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
187 return function (callable $handler) use ($logger, $formatter, $logLevel) {
188 return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) {
189 return $handler($request, $options)->then(
190 function ($response) use ($logger, $request, $formatter, $logLevel) {
191 $message = $formatter->format($request, $response);
192 $logger->log($logLevel, $message);
195 function ($reason) use ($logger, $request, $formatter) {
196 $response = $reason instanceof RequestException
197 ? $reason->getResponse()
199 $message = $formatter->format($request, $response, $reason);
200 $logger->notice($message);
201 return \GuzzleHttp\Promise\rejection_for($reason);
209 * This middleware adds a default content-type if possible, a default
210 * content-length or transfer-encoding header, and the expect header.
214 public static function prepareBody()
216 return function (callable $handler) {
217 return new PrepareBodyMiddleware($handler);
222 * Middleware that applies a map function to the request before passing to
225 * @param callable $fn Function that accepts a RequestInterface and returns
226 * a RequestInterface.
229 public static function mapRequest(callable $fn)
231 return function (callable $handler) use ($fn) {
232 return function ($request, array $options) use ($handler, $fn) {
233 return $handler($fn($request), $options);
239 * Middleware that applies a map function to the resolved promise's
242 * @param callable $fn Function that accepts a ResponseInterface and
243 * returns a ResponseInterface.
246 public static function mapResponse(callable $fn)
248 return function (callable $handler) use ($fn) {
249 return function ($request, array $options) use ($handler, $fn) {
250 return $handler($request, $options)->then($fn);