Total Complexity | 10 |
Total Lines | 89 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | <?php |
||
13 | class Bucket |
||
14 | { |
||
15 | /** |
||
16 | * Overall generating interval in ms |
||
17 | */ |
||
18 | private const GMS = 1000; |
||
19 | |||
20 | /** |
||
21 | * How many TICK in once generating loop |
||
22 | */ |
||
23 | private const PST = 10; |
||
24 | |||
25 | /** |
||
26 | * @var Options |
||
27 | */ |
||
28 | private $options = null; |
||
29 | |||
30 | /** |
||
31 | * @var int |
||
32 | */ |
||
33 | private $tokens = 0; |
||
34 | |||
35 | /** |
||
36 | * @var string |
||
37 | */ |
||
38 | private $generator = null; |
||
39 | |||
40 | /** |
||
41 | * @var callable |
||
42 | */ |
||
43 | private $watcher = null; |
||
44 | |||
45 | /** |
||
46 | * Bucket constructor. |
||
47 | * @param Options $options |
||
48 | * @param callable $watcher |
||
49 | */ |
||
50 | public function __construct(Options $options, callable $watcher = null) |
||
51 | { |
||
52 | $this->options = $options; |
||
53 | |||
54 | $this->tokens = $options->capacity; |
||
55 | |||
56 | $this->watcher = $watcher; |
||
57 | $this->generator = Timer::loop(self::GMS / self::PST, [$this, 'in']); |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | */ |
||
62 | public function stop() : void |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * @return int |
||
69 | */ |
||
70 | public function tokens() : int |
||
71 | { |
||
72 | return $this->tokens; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * tokens in |
||
77 | */ |
||
78 | public function in() : void |
||
79 | { |
||
80 | $this->tokens += intval($this->options->bucketTGS / self::PST); |
||
81 | |||
82 | $this->options->capacity > 0 |
||
83 | ? $this->tokens > $this->options->capacity && $this->tokens = $this->options->capacity |
||
84 | : $this->tokens > $this->options->bucketTGS && $this->tokens = $this->options->bucketTGS |
||
85 | ; |
||
86 | |||
87 | ($c = $this->watcher) && $c($this); |
||
88 | } |
||
89 | |||
90 | /** |
||
91 | * tokens out |
||
92 | * @param int $n |
||
93 | * @return bool |
||
94 | */ |
||
95 | public function out(int $n) : bool |
||
102 | } |
||
103 | } |
||
104 | } |
||
105 |