-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoundRobinThrottler.php
36 lines (28 loc) · 1.12 KB
/
RoundRobinThrottler.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
<?php
declare(strict_types=1);
namespace Orangesoft\Throttler;
use Orangesoft\Throttler\Collection\CollectionInterface;
use Orangesoft\Throttler\Collection\NodeInterface;
use Orangesoft\Throttler\Counter\CounterInterface;
final class RoundRobinThrottler implements ThrottlerInterface
{
public function __construct(
private CounterInterface $counter,
) {
}
/**
* @param array<string, mixed> $context
*/
public function pick(CollectionInterface $collection, array $context = []): NodeInterface
{
if ($collection->isEmpty()) {
throw new \RuntimeException('Collection of nodes mustn\'t be empty.'); // @codeCoverageIgnore
}
if (isset($context['counter']) && !\is_string($context['counter'])) {
throw new \RuntimeException(\sprintf('The parameter "counter" must be as a string, %s given.', get_debug_type($context['counter']))); // @codeCoverageIgnore
}
$counter = $context['counter'] ?? spl_object_hash($collection);
$key = $this->counter->next($counter) % \count($collection);
return $collection->get($key);
}
}