Completed
Pull Request — master (#127)
by thomas
58:41 queued 39:41
created

Throttler::waitForThrottle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 3
rs 9.7998
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 4
    public function __construct($interval) {
20 4
        $this->interval = $interval;
21 4
    }
22
23 6
    public function waitForThrottle() {
24 6
        if (!$this->lastTime) {
25 3
            $this->lastTime = \microtime(true);
26 3
            return;
27
        }
28
29 5
        $diff = $this->interval - (\microtime(true) - $this->lastTime);
30
31 5
        if ($diff > 0) {
32 1
            usleep((int)ceil($diff * 1000 * 1000));
33
        }
34
35 5
        $this->lastTime = \microtime(true);
36 5
    }
37
38
    private static $instances = [];
39
40 80
    public static function getInstance($key, $interval) {
41 80
        if (!isset(self::$instances[$key])) {
42 3
            self::$instances[$key] = new Throttler($interval);
43
        }
44
45 80
        return self::$instances[$key];
46
    }
47
}
48