<?php

namespace Dipper\Foundation\Http\GuzzleMiddlewares;

use Log;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Class RetryMiddleware.
 */
class RetryMiddleware extends MiddlewareAbstract
{
    public function handle()
    {
        return Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null) {
            // Limit the number of retries
            if ($retries <= config('dipper.guzzle.retry_middleware_retries') && $response && $response->getStatusCode() === 500) {
                // Retry on server errors
                Log::debug("Guzzle 请求重试 : 第 {$retries} 次");

                return true;
            }

            return false;
        });
    }

    public function getMiddlewareName()
    {
        return 'retry_middleware';
    }
}
