@@ -50,6 +50,20 @@ class PendingRequest
50
50
*/
51
51
protected $ options = [];
52
52
53
+ /**
54
+ * The number of times to try the request.
55
+ *
56
+ * @var int
57
+ */
58
+ protected $ tries = 1 ;
59
+
60
+ /**
61
+ * The number of milliseconds to wait between retries.
62
+ *
63
+ * @var int
64
+ */
65
+ protected $ retryDelay = 100 ;
66
+
53
67
/**
54
68
* The callbacks that should execute before the request is sent.
55
69
*
@@ -300,6 +314,21 @@ public function timeout(int $seconds)
300
314
});
301
315
}
302
316
317
+ /**
318
+ * Specify the number of times the request should be attempted.
319
+ *
320
+ * @param int $times
321
+ * @param int $sleep
322
+ * @return $this
323
+ */
324
+ public function retry (int $ times , int $ sleep = 0 )
325
+ {
326
+ $ this ->tries = $ times ;
327
+ $ this ->retryDelay = $ sleep ;
328
+
329
+ return $ this ;
330
+ }
331
+
303
332
/**
304
333
* Merge new options into the client.
305
334
*
@@ -414,20 +443,26 @@ public function send(string $method, string $url, array $options = [])
414
443
415
444
$ this ->pendingFiles = [];
416
445
417
- try {
418
- return tap (new Response ($ this ->buildClient ()->request ($ method , $ url , $ this ->mergeOptions ([
419
- 'laravel_data ' => $ options [$ this ->bodyFormat ] ?? [],
420
- 'query ' => $ this ->parseQueryParams ($ url ),
421
- 'on_stats ' => function ($ transferStats ) {
422
- $ this ->transferStats = $ transferStats ;
423
- },
424
- ], $ options ))), function ($ response ) {
425
- $ response ->cookies = $ this ->cookies ;
426
- $ response ->transferStats = $ this ->transferStats ;
427
- });
428
- } catch (\GuzzleHttp \Exception \ConnectException $ e ) {
429
- throw new ConnectionException ($ e ->getMessage (), 0 , $ e );
430
- }
446
+ return retry ($ this ->tries ?? 1 , function () use ($ method , $ url , $ options ) {
447
+ try {
448
+ return tap (new Response ($ this ->buildClient ()->request ($ method , $ url , $ this ->mergeOptions ([
449
+ 'laravel_data ' => $ options [$ this ->bodyFormat ] ?? [],
450
+ 'query ' => $ this ->parseQueryParams ($ url ),
451
+ 'on_stats ' => function ($ transferStats ) {
452
+ $ this ->transferStats = $ transferStats ;
453
+ },
454
+ ], $ options ))), function ($ response ) {
455
+ $ response ->cookies = $ this ->cookies ;
456
+ $ response ->transferStats = $ this ->transferStats ;
457
+
458
+ if ($ this ->tries > 1 && ! $ response ->successful ()) {
459
+ $ response ->throw ();
460
+ }
461
+ });
462
+ } catch (\GuzzleHttp \Exception \ConnectException $ e ) {
463
+ throw new ConnectionException ($ e ->getMessage (), 0 , $ e );
464
+ }
465
+ }, $ this ->retryDelay ?? 100 );
431
466
}
432
467
433
468
/**
0 commit comments