RedisSingleInstanceLock   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 55
c 0
b 0
f 0
wmc 5
lcom 1
cbo 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A acquireLock() 0 9 2
A releaseLock() 0 12 2
1
<?php
2
/**
3
 * @filename RedisSingleInstanceLock.php
4
 * @touch    10/01/2017 14:17
5
 * @author   wudege <[email protected]>
6
 * @version  1.0.0
7
 */
8
9
namespace Sil;
10
11
use Predis\Client;
12
use Predis\Response\Status;
13
14
class RedisSingleInstanceLock implements LockInterface
15
{
16
17
    /**
18
     * @var Client
19
     */
20
    private $client;
21
22
    public function __construct(Client $client)
23
    {
24
        $this->client = $client;
25
    }
26
27
    /**
28
     *
29
     * @author wudege <[email protected]>
30
     *
31
     * @param $lockName
32
     * @param $identifier
33
     * @param $timeoutMilliseconds
34
     *
35
     * @return bool
36
     */
37
    public function acquireLock($lockName, $identifier, $timeoutMilliseconds)
38
    {
39
        $status = $this->client->set($lockName, $identifier, 'PX', $timeoutMilliseconds, 'NX');
40
        if ($status instanceof Status) {
41
            return $status->getPayload() === 'OK';
42
        }
43
44
        return false;
45
    }
46
47
    /**
48
     *
49
     * @author wudege <[email protected]>
50
     *
51
     * @param $lockName
52
     * @param $identifier
53
     *
54
     * @return bool
55
     */
56
    public function releaseLock($lockName, $identifier)
57
    {
58
        $luaScript = <<<LUA
59
if redis.call("get",KEYS[1]) == ARGV[1] then
60
    return redis.call("del",KEYS[1])
61
else
62
    return 0
63
end
64
LUA;
65
66
        return $this->client->eval($luaScript, 1, $lockName, $identifier) ? true : false;
67
    }
68
}