Bucket::tokens()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Bucket with tokens
4
 * User: moyo
5
 * Date: 19/08/2017
6
 * Time: 11:42 AM
7
 */
8
9
namespace Carno\Shaping;
10
11
use Carno\Timer\Timer;
12
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
63
    {
64
        Timer::clear($this->generator);
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
96
    {
97
        if ($n <= $this->tokens) {
98
            $this->tokens -= $n;
99
            return true;
100
        } else {
101
            return false;
102
        }
103
    }
104
}
105