|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Providers; |
| 4 | + |
| 5 | +use GuzzleHttp\Client; |
| 6 | +use GuzzleHttp\Exception\ConnectException; |
| 7 | +use GuzzleHttp\Handler\CurlHandler; |
| 8 | +use GuzzleHttp\HandlerStack; |
| 9 | +use GuzzleHttp\Middleware; |
| 10 | +use GuzzleHttp\Psr7\Request; |
| 11 | +use GuzzleHttp\Psr7\Response; |
| 12 | +use Illuminate\Support\ServiceProvider; |
| 13 | + |
| 14 | +class HttpclientServiceProvider extends ServiceProvider |
| 15 | +{ |
| 16 | + /** |
| 17 | + * Register services. |
| 18 | + * |
| 19 | + * @return void |
| 20 | + */ |
| 21 | + public function register() |
| 22 | + { |
| 23 | + $this->app->singleton(Client::class, function ($app) { |
| 24 | + $handlerStack = HandlerStack::create(new CurlHandler()); |
| 25 | + $handlerStack->push( |
| 26 | + Middleware::retry( |
| 27 | + function ( |
| 28 | + $retries, |
| 29 | + Request $request, |
| 30 | + Response $response = null, |
| 31 | + \Throwable $exception = null |
| 32 | + ) { |
| 33 | + // Limit the number of retries to 3 |
| 34 | + if ($retries >= 3) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + // Retry connection exceptions |
| 39 | + if ($exception instanceof ConnectException) { |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + if ($response) { |
| 44 | + // Retry on server errors |
| 45 | + if ($response->getStatusCode() >= 500) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return false; |
| 51 | + }, |
| 52 | + function ($numberOfRetries) { |
| 53 | + return 1000 * $numberOfRetries; |
| 54 | + } |
| 55 | + ) |
| 56 | + ); |
| 57 | + |
| 58 | + return new Client([ |
| 59 | + 'handler' => $handlerStack, |
| 60 | + 'allow_redirects' => [ |
| 61 | + 'max' => 5, |
| 62 | + 'strict' => true, // "strict" redirects - that's key as a redirected POST stays a POST |
| 63 | + 'referer' => true, |
| 64 | + 'track_redirects' => true |
| 65 | + ], |
| 66 | + 'headers' => [ |
| 67 | + 'User-Agent' => 'Joomla.org Automated Updates Server', |
| 68 | + 'Accept-Encoding' => 'gzip, deflate' |
| 69 | + ], |
| 70 | + 'verify' => false |
| 71 | + ]); |
| 72 | + }); |
| 73 | + } |
| 74 | +} |
0 commit comments