3 declare(strict_types=1);
12 use GuzzleHttp\Exception\ServerException;
13 use GuzzleHttp\MessageFormatter;
14 use GuzzleHttp\Middleware;
15 use GuzzleHttp\Promise\PromiseInterface;
16 use Psr\Http\Message\RequestInterface;
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Log\LoggerInterface;
28 ?LoggerInterface $logger =
null,
33 if (!is_null($handler)) {
37 if (!is_null($logger)) {
40 if ($maxRetries > 0) {
53 return Middleware::mapRequest(
54 function (RequestInterface $request) use ($correlationIdProvider) {
55 return $request->withAddedHeader(
68 return Middleware::retry(
71 RequestInterface $request,
72 ResponseInterface $response =
null,
73 \Exception $error =
null
75 if ($response instanceof ResponseInterface && $response->getStatusCode() < 500) {
78 if ($retries < $maxRetries) {
81 if ($error instanceof ServerException && $error->getCode() == 503) {
84 if ($response instanceof ResponseInterface && $response->getStatusCode() == 503) {
97 return Middleware::mapRequest($handler);
104 public static function createLoggerMiddleware(LoggerInterface $logger,
string $logLevel = LogLevel::INFO,
string $template = MessageFormatter::CLF)
106 return Middleware::log($logger,
new MessageFormatter($template), $logLevel);
121 function (callable $handler) use ($oauthHandler, $maxRetries) {
127 function (RequestInterface $request, array $options) use ($handler, $oauthHandler, $maxRetries): PromiseInterface {
128 return $handler($request, $options)->then(
129 function (ResponseInterface $response) use (
136 if ($response->getStatusCode() == 401) {
137 if (!isset($options[
'reauth'])) {
138 $options[
'reauth'] = 0;
140 if ($options[
'reauth'] < $maxRetries) {
141 $options[
'reauth']++;
143 $request = $request->withHeader(
145 'Bearer ' . $token->getValue()
147 return $handler($request, $options);