add middleware to retry request in some error cases

This commit is contained in:
Daniel Seifert 2023-01-18 11:07:49 +01:00
parent a50567fd0c
commit 1e2582a76b
Signed by: DanielS
GPG Key ID: 8A7C4C6ED1915C6F
3 changed files with 62 additions and 6 deletions

View File

@ -246,4 +246,38 @@ class ClientTest extends ApiTestCase
) )
); );
} }
/**
* @test
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @covers \D3\LinkmobilityClient\Client::getLoggerMiddleware
*/
public function testGetLoggerMiddleware()
{
$this->assertIsCallable(
$this->callMethod(
$this->api,
'getLoggerMiddleware'
)
);
}
/**
* @test
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @covers \D3\LinkmobilityClient\Client::getRetryMiddleware
*/
public function testGetRetryMiddleware()
{
$this->assertIsCallable(
$this->callMethod(
$this->api,
'getRetryMiddleware'
)
);
}
} }

View File

@ -27,6 +27,7 @@
"psr/http-message": "~1.0", "psr/http-message": "~1.0",
"phlib/sms-length": "^2.0", "phlib/sms-length": "^2.0",
"giggsey/libphonenumber-for-php": "^8.12.50", "giggsey/libphonenumber-for-php": "^8.12.50",
"caseyamcl/guzzle_retry_middleware": "^2.8",
"ext-json": "*" "ext-json": "*"
}, },
"require-dev": { "require-dev": {

View File

@ -24,6 +24,7 @@ use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack; use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter; use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware; use GuzzleHttp\Middleware;
use GuzzleRetry\GuzzleRetryMiddleware;
use InvalidArgumentException; use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -45,13 +46,9 @@ class Client
*/ */
protected function getDefaultClient(): GuzzleClient protected function getDefaultClient(): GuzzleClient
{ {
$logger = Middleware::log(
$this->getLoggerHandler()->getLogger(),
new MessageFormatter(MessageFormatter::DEBUG),
'debug'
);
$handlerStack = HandlerStack::create(); $handlerStack = HandlerStack::create();
$handlerStack->push($logger); $handlerStack->push($this->getLoggerMiddleware());
$handlerStack->push($this->getRetryMiddleware());
return new GuzzleClient( [ return new GuzzleClient( [
'base_uri' => $this->apiUrl->getBaseUri(), 'base_uri' => $this->apiUrl->getBaseUri(),
@ -100,4 +97,28 @@ class Client
{ {
return LoggerHandler::getInstance(); return LoggerHandler::getInstance();
} }
/**
* @param string $loglevel
*
* @return callable
*/
protected function getLoggerMiddleware(string $loglevel = 'debug'): callable
{
return Middleware::log(
$this->getLoggerHandler()->getLogger(),
new MessageFormatter(MessageFormatter::DEBUG),
$loglevel
);
}
/**
* @return callable
*/
protected function getRetryMiddleware(): callable
{
return GuzzleRetryMiddleware::factory([
'max_retry_attempts' => 3
]);
}
} }