This repository was archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathLock.php
108 lines (90 loc) · 2.03 KB
/
Lock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace SDK;
class Lock
{
protected $fd;
protected $fn;
protected $locked = false;
protected $wouldBlock = false;
protected $shared = false;
public function __construct(string $tag, bool $auto = true, bool $autoShared = false)
{/*{{{*/
$hash = hash("sha256", $tag);
$this->fn = Config::getTmpDir() . DIRECTORY_SEPARATOR . $hash . ".lock";
if ($auto) {
if ($autoShared) {
$this->shared();
} else {
$this->exclusive();
}
}
}/*}}}*/
public function __destruct()
{/*{{{*/
$this->unlock();
/* We don't really know no one else waits on the same lock yet.*/
/*if (file_exists($this->fn) && !$this->shared) {
@unlink($this->fn);
}*/
}/*}}}*/
public function shared(bool $block = false) : bool
{/*{{{*/
$flags = LOCK_SH;
if (!$block) {
$flags |= LOCK_NB;
}
return $this->doLock($flags);
}/*}}}*/
public function exclusive(bool $block = false) : bool
{/*{{{*/
$flags = LOCK_EX;
if (!$block) {
$flags |= LOCK_NB;
}
return $this->doLock($flags);
}/*}}}*/
protected function doLock(int $flags = LOCK_EX) : bool
{/*{{{*/
if ($this->locked) {
/* Or throw an exception, as we don't know which lock type the outta world expected. */
return true;
}
$this->shared = $flags & LOCK_SH;
if ($this->shared) {
$this->fd = fopen($this->fn, "rb");
} else {
$this->fd = fopen($this->fn, "wb");
}
if (false === $this->fd) {
throw new Exception("Failed to open lock under '$this->fn'");
}
$this->locked = flock($this->fd, $flags, $this->wouldBlock);
return $this->locked;
}/*}}}*/
public function unlock() : bool
{/*{{{*/
if (!$this->locked) {
return true;
}
$this->doLock(LOCK_UN);
fclose($this->fd);
$this->fd = NULL;
return $this->locked;
}/*}}}*/
public function locked() : bool
{/*{{{*/
return $this->locked;
}/*}}}*/
public function wouldBlock() : bool
{/*{{{*/
return 1 === $this->wouldBlock;
}/*}}}*/
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/