1
|
|
|
<?php |
2
|
|
|
namespace PHPDaemon\Clients\Redis; |
3
|
|
|
|
4
|
|
|
use PHPDaemon\Utils\Crypt; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* @package NetworkClients |
8
|
|
|
* @subpackage RedisClient |
9
|
|
|
* @author Vasily Zorin <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
class Lock |
12
|
|
|
{ |
13
|
|
|
use \PHPDaemon\Traits\ClassWatchdog; |
14
|
|
|
use \PHPDaemon\Traits\StaticObjectWatchdog; |
15
|
|
|
|
16
|
|
|
protected $pool; |
17
|
|
|
protected $timeout; |
18
|
|
|
protected $token; |
19
|
|
|
protected $key; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Constructor |
23
|
|
|
* @param string $key |
24
|
|
|
* @param integer $timeout |
25
|
|
|
* @param Pool $pool |
26
|
|
|
*/ |
27
|
|
|
public function __construct($key, $timeout, $pool) |
28
|
|
|
{ |
29
|
|
|
$this->pool = $pool; |
30
|
|
|
$this->timeout = $timeout; |
31
|
|
|
$this->key = $key; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @TODO |
36
|
|
|
* @param integer $timeout |
37
|
|
|
* @return this |
|
|
|
|
38
|
|
|
*/ |
39
|
|
|
public function timeout($timeout) |
40
|
|
|
{ |
41
|
|
|
$this->timeout = $timeout; |
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @TODO |
47
|
|
|
* @param callable $cb |
48
|
|
|
* @callback $cb ( ) |
49
|
|
|
* @return this |
|
|
|
|
50
|
|
|
*/ |
51
|
|
|
public function acquire($cb) |
52
|
|
|
{ |
53
|
|
|
Crypt::randomString(16, null, function ($token) use ($cb) { |
54
|
|
|
$this->token = $token; |
55
|
|
|
$this->pool->set($this->key, $this->token, 'NX', 'EX', $this->timeout, function ($redis) use ($cb) { |
|
|
|
|
56
|
|
|
$cb($this, $redis->result === 'OK', $redis); |
57
|
|
|
}); |
58
|
|
|
}); |
59
|
|
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @TODO |
64
|
|
|
* @param callable $cb |
|
|
|
|
65
|
|
|
* @callback $cb ( ) |
66
|
|
|
* @return this |
|
|
|
|
67
|
|
|
*/ |
68
|
|
|
public function release($cb = null) |
69
|
|
|
{ |
70
|
|
|
$this->pool->eval( |
|
|
|
|
71
|
|
|
'if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end', |
72
|
|
|
1, |
73
|
|
|
$this->key, |
74
|
|
|
$this->token, |
75
|
|
|
function ($redis) use ($cb) { |
76
|
|
|
if ($cb !== null) { |
77
|
|
|
$cb($this, $redis->result, $redis); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
); |
81
|
|
|
|
82
|
|
|
return $this; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check compares the return type specified in the
@return
annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.