@@ -15,6 +15,7 @@ class Lock
15
15
static private $ data = [];
16
16
static private $ dir = null ;
17
17
static private $ keyPrefix = null ;
18
+ static private $ defaultLockTimeout = 1.5 ;
18
19
19
20
/**
20
21
*
@@ -52,6 +53,24 @@ static function setKeyPrefix($prefix)
52
53
self ::$ keyPrefix = $ prefix ;
53
54
}
54
55
56
+ /**
57
+ *
58
+ * @return string
59
+ */
60
+ static function getDefaultLockTimeout ()
61
+ {
62
+ return self ::$ defaultLockTimeout ;
63
+ }
64
+
65
+ /**
66
+ *
67
+ * @param string $prefix
68
+ */
69
+ static function setDefaultLockTimeout ($ seconds )
70
+ {
71
+ self ::$ defaultLockTimeout = $ seconds ;
72
+ }
73
+
55
74
/**
56
75
*
57
76
* @param mixed $key
@@ -61,7 +80,7 @@ static function setKeyPrefix($prefix)
61
80
static public function acquire ($ key , $ options = [])
62
81
{
63
82
$ keyMD5 = md5 (self ::$ keyPrefix . serialize ($ key ));
64
- $ timeout = isset ($ options ['timeout ' ]) ? (float ) $ options ['timeout ' ] : 1.5 ;
83
+ $ timeout = isset ($ options ['timeout ' ]) ? (float ) $ options ['timeout ' ] : self :: $ defaultLockTimeout ;
65
84
$ retryInterval = 0.5 ;
66
85
$ maxRetriesCount = floor ($ timeout / $ retryInterval );
67
86
$ lock = function () use ($ keyMD5 ) {
@@ -118,7 +137,11 @@ static public function acquire($key, $options = [])
118
137
static public function exists ($ key )
119
138
{
120
139
$ keyMD5 = md5 (self ::$ keyPrefix . serialize ($ key ));
121
- $ filename = self ::getLocksDir () . $ keyMD5 . '.lock ' ;
140
+ $ dir = self ::getLocksDir ();
141
+ if (!is_dir ($ dir )) {
142
+ return false ;
143
+ }
144
+ $ filename = $ dir . $ keyMD5 . '.lock ' ;
122
145
set_error_handler (function ($ errno , $ errstr ) {
123
146
throw new \Exception ($ errstr );
124
147
});
@@ -151,6 +174,9 @@ static public function release($key)
151
174
$ keyMD5 = md5 (self ::$ keyPrefix . serialize ($ key ));
152
175
if (!isset (self ::$ data [$ keyMD5 ])) {
153
176
throw new \Exception ('A lock name " ' . $ key . '" does not exists in current process! ' );
177
+ }
178
+ $ dir = self ::getLocksDir ();
179
+ if (!is_dir ($ dir )) {
154
180
return ;
155
181
}
156
182
set_error_handler (function ($ errno , $ errstr ) {
@@ -159,7 +185,7 @@ static public function release($key)
159
185
try {
160
186
if (flock (self ::$ data [$ keyMD5 ], LOCK_UN ) && fclose (self ::$ data [$ keyMD5 ])) {
161
187
try {
162
- $ filename = self :: getLocksDir () . $ keyMD5 . '.lock ' ;
188
+ $ filename = $ dir . $ keyMD5 . '.lock ' ;
163
189
$ tempFilename = $ filename . '. ' . md5 (uniqid () . rand (0 , 999999 ));
164
190
$ renameResult = rename ($ filename , $ tempFilename );
165
191
if ($ renameResult ) {
0 commit comments