/
SleepClient.php
47 lines (39 loc) · 1.25 KB
/
SleepClient.php
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
<?php declare(strict_types=1);
namespace StrictPhp\HttpClients\Clients\Sleep;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use StrictPhp\HttpClients\Helpers\Time;
use StrictPhp\HttpClients\Managers\ConfigManager;
final class SleepClient implements ClientInterface
{
/**
* @var array<string, float>
*/
private array $timeout = [];
public function __construct(
private readonly ClientInterface $client,
private readonly ConfigManager $configManager,
) {
}
public function sendRequest(RequestInterface $request): ResponseInterface
{
$host = $request->getUri()
->getHost();
$config = $this->configManager->get(Config::class, $host);
if ($config->to > 0 && isset($this->timeout[$host])) {
$diff = Time::micro() - $this->timeout[$host];
if ($diff < 1) {
Time::sleep(random_int($config->from, $config->to));
}
}
try {
$response = $this->client->sendRequest($request);
} finally {
if ($config->to > 0) {
$this->timeout[$host] = Time::micro();
}
}
return $response;
}
}