1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of SteamScore. |
7
|
|
|
* |
8
|
|
|
* (c) SteamScore <[email protected]> |
9
|
|
|
* |
10
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public |
11
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this |
12
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace SteamScore\Api\Domain\Managers; |
16
|
|
|
|
17
|
|
|
use bandwidthThrottle\tokenBucket\Rate; |
18
|
|
|
use bandwidthThrottle\tokenBucket\storage\PredisStorage; |
19
|
|
|
use bandwidthThrottle\tokenBucket\TokenBucket; |
20
|
|
|
use Predis\Client; |
21
|
|
|
use SteamScore\Api\Domain\Exceptions\InvalidBucketException; |
22
|
|
|
use SteamScore\Api\Domain\Interfaces\BucketManagerInterface; |
23
|
|
|
|
24
|
|
|
final class BucketManager implements BucketManagerInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
private $buckets = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Constructor. |
33
|
|
|
* |
34
|
|
|
* @param Client $client |
35
|
|
|
* @param array $buckets |
36
|
|
|
*/ |
37
|
|
|
public function __construct(Client $client, array $buckets) |
38
|
|
|
{ |
39
|
|
|
foreach ($buckets as $name => $bucket) { |
40
|
|
|
$storage = new PredisStorage(sprintf('bucket:%s', $name), $client); |
41
|
|
|
$rate = new Rate($bucket['tokens'], $bucket['unit']); |
42
|
|
|
$this->buckets[$name] = new TokenBucket($bucket['capacity'], $rate, $storage); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
|
|
public function getAll(): array |
50
|
|
|
{ |
51
|
|
|
return $this->buckets; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* {@inheritdoc} |
56
|
|
|
*/ |
57
|
|
|
public function getByName(string $name): TokenBucket |
58
|
|
|
{ |
59
|
|
|
if (array_key_exists($name, $this->buckets) === false) { |
60
|
|
|
throw new InvalidBucketException(sprintf('Unknown bucket "%s"', $name)); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $this->buckets[$name]; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|