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