-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeightedRandomThrottler.php
39 lines (30 loc) · 1.21 KB
/
WeightedRandomThrottler.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
<?php
declare(strict_types=1);
namespace Orangesoft\Throttler;
use Orangesoft\Throttler\Collection\CollectionInterface;
use Orangesoft\Throttler\Collection\NodeInterface;
final class WeightedRandomThrottler implements ThrottlerInterface
{
/**
* @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
}
$currentWeight = 0;
$sumWeight = array_sum(array_map(static fn (NodeInterface $node): int => $node->getWeight(), $collection->toArray()));
$randomWeight = mt_rand(1, $sumWeight);
foreach ($collection as $node) {
if (0 === $node->getWeight()) {
throw new \RuntimeException('All nodes in the collection must be weighted.'); // @codeCoverageIgnore
}
$currentWeight += $node->getWeight();
if ($randomWeight <= $currentWeight) {
return $node;
}
}
throw new \RuntimeException('You never will catch this exception.'); // @codeCoverageIgnore
}
}