1 | <?php |
||
23 | final class RetryMiddleware implements Middleware |
||
24 | { |
||
25 | private const DEFAULT_MAX_RETRIES = 2; |
||
26 | |||
27 | /** @var \Closure */ |
||
28 | private $getDelayMs; |
||
29 | |||
30 | /** |
||
31 | * @param \Closure $getDelayMs |
||
32 | */ |
||
33 | 15 | private function __construct($getDelayMs) |
|
37 | |||
38 | public static function constant(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $intervalMs = 100) : self |
||
39 | { |
||
40 | return new self(static function (int $retries) use ($maxRetries, $intervalMs) { |
||
41 | return $retries > $maxRetries ? null : $intervalMs; |
||
42 | }); |
||
43 | } |
||
44 | |||
45 | public static function exponential(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $baseMs = 100) : self |
||
46 | { |
||
47 | return new self(static function (int $retries) use ($maxRetries, $baseMs) { |
||
48 | return $retries > $maxRetries ? null : $baseMs ** $retries; |
||
49 | }); |
||
50 | } |
||
51 | |||
52 | 9 | public static function linear(int $maxRetries = self::DEFAULT_MAX_RETRIES, int $differenceMs = 100) : self |
|
53 | { |
||
54 | 9 | return new self(static function (int $retries) use ($maxRetries, $differenceMs) { |
|
55 | 6 | return $retries > $maxRetries ? null : $differenceMs * $retries; |
|
56 | 9 | }); |
|
57 | } |
||
58 | |||
59 | 6 | public static function custom(\Closure $getDelayMs) : self |
|
60 | { |
||
61 | 6 | return new self(static function (int $retries, \Throwable $e) use ($getDelayMs) : ?int { |
|
62 | 6 | return $getDelayMs($retries, $e); |
|
63 | 6 | }); |
|
64 | } |
||
65 | |||
66 | 15 | public function process(Request $request, Handler $handler) : Response |
|
90 | } |
||
91 |