RedisTicker   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 57
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 1
A tick() 0 20 2
A getConnection() 0 4 1
1
<?php
2
namespace pastuhov\yii2redisticker;
3
4
use Yii;
5
use yii\base\Component;
6
use yii\redis\Connection;
7
use yii\di\Instance;
8
9
/**
10
 * Redis ticker.
11
 */
12
class RedisTicker extends Component
13
{
14
15
    /**
16
     * @var \yii\redis\Connection
17
     */
18
    public $redis;
19
20
    /**
21
     * Init.
22
     *
23
     * @throws \yii\base\InvalidConfigException
24
     */
25
    public function init()
26
    {
27
        parent::init();
28
        $this->redis = Instance::ensure($this->redis, Connection::className());
29
30
    }
31
32
    /**
33
     * Acquires tick by given name.
34
     *
35
     * @param string $name of the tick to be acquired.
36
     * @param integer $timeout to wait for tick to become released.
37
     *
38
     * @return boolean tick result.
39
     */
40
    public function tick($name, $timeout = 1)
41
    {
42
        $redis = $this->getConnection();
43
        $tickValue = 1;
44
        $params = [
45
            $name, // Key name
46
            $tickValue, // Key value
47
            'NX', // Set if Not eXists
48
            'EX', // Expire time
49
            $timeout // Seconds
50
        ];
51
        $response = $redis->executeCommand('SET', $params);
52
53
        if ($response === true) {
54
55
            return true;
56
        }
57
58
        return false;
59
    }
60
61
    /**
62
     * @return \yii\redis\Connection
63
     */
64
    protected function getConnection()
65
    {
66
        return $this->redis;
67
    }
68
}
69