Completed
Pull Request — master (#125)
by thomas
52:19 queued 50:02
created

Throttler::waitForThrottle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 15
ccs 9
cts 10
cp 0.9
crap 3.009
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace Blocktrail\SDK;
4
5
class Throttler {
6
7
    /**
8
     * @var float|null
9
     */
10
    private $lastTime = null;
11
12
    /**
13
     * interval to wait in seconds, can be float
14
     *
15
     * @var float
16
     */
17
    private $interval;
18
19 3
    public function __construct($interval) {
20 3
        $this->interval = $interval;
21 3
    }
22
23 5
    public function waitForThrottle() {
24 5
        if (!$this->lastTime) {
25 2
            $this->lastTime = \microtime(true);
26 2
            return;
27
        }
28
29 4
        $now = \microtime(true);
30 4
        $diff = $this->interval - ($now - $this->lastTime);
31
32 4
        if ($diff > 0) {
33
            usleep((int)ceil($diff * 1000 * 1000));
34
        }
35
36 4
        $this->lastTime = \microtime(true);
37 4
    }
38
39
    private static $instances = [];
40
41 65
    public static function getInstance($key, $interval) {
42 65
        if (!isset(self::$instances[$key])) {
43 3
            self::$instances[$key] = new Throttler($interval);
44
        }
45
46 65
        return self::$instances[$key];
47
    }
48
}
49