RetryMiddleware.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Guzzle;
  12. use GuzzleHttp\Middleware;
  13. use Psr\Http\Message\RequestInterface;
  14. use Psr\Http\Message\ResponseInterface;
  15. class RetryMiddleware implements MiddlewareInterface
  16. {
  17. public function __construct(protected int $retries = 1, protected int $delay = 0)
  18. {
  19. }
  20. public function getMiddleware(): callable
  21. {
  22. return Middleware::retry(function ($retries, RequestInterface $request, ?ResponseInterface $response = null) {
  23. if (! $this->isOk($response) && $retries < $this->retries) {
  24. return true;
  25. }
  26. return false;
  27. }, function () {
  28. return $this->delay;
  29. });
  30. }
  31. /**
  32. * Check the response status is correct.
  33. */
  34. protected function isOk(?ResponseInterface $response): bool
  35. {
  36. return $response && $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
  37. }
  38. }