1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
<?php
namespace Gedcomx\Extensions\FamilySearch\Rs\Client\Util;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\MessageInterface;
class ThrottlingMiddleware
{
public static $maxRetries = 2;
public static function middleware()
{
return function (callable $handler) {
return new ThrottlingMiddleware($handler);
};
}
private $nextHandler;
public function __construct(callable $nextHandler)
{
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options)
{
$fn = $this->nextHandler;
return $fn($request, $options)
->then(function (ResponseInterface $response) use ($request, $options) {
return $this->checkThrottling($request, $options, $response);
});
}
public function checkThrottling(
RequestInterface $request,
array $options,
ResponseInterface $response
) {
if(!isset($options['__throttle_retries'])){
$options['__throttle_retries'] = $this::$maxRetries;
}
if ($response->getStatusCode() !== 429 || !($options['__throttle_retries'] > 0)) {
return $response;
}
$options['__throttle_retries']--;
sleep($response->getHeader('Retry-After')[0]);
$promise = $this($request, $options);
return $promise->then(
function (ResponseInterface $response) {
return $response->withHeader('X-FS-THROTTLED', '');
}
);
}
}