@@ -15,6 +15,7 @@ class Lock
1515 static private $ data = [];
1616 static private $ dir = null ;
1717 static private $ keyPrefix = null ;
18+ static private $ defaultLockTimeout = 1.5 ;
1819
1920 /**
2021 *
@@ -52,6 +53,24 @@ static function setKeyPrefix($prefix)
5253 self ::$ keyPrefix = $ prefix ;
5354 }
5455
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+
5574 /**
5675 *
5776 * @param mixed $key
@@ -61,7 +80,7 @@ static function setKeyPrefix($prefix)
6180 static public function acquire ($ key , $ options = [])
6281 {
6382 $ 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 ;
6584 $ retryInterval = 0.5 ;
6685 $ maxRetriesCount = floor ($ timeout / $ retryInterval );
6786 $ lock = function () use ($ keyMD5 ) {
@@ -118,7 +137,11 @@ static public function acquire($key, $options = [])
118137 static public function exists ($ key )
119138 {
120139 $ 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 ' ;
122145 set_error_handler (function ($ errno , $ errstr ) {
123146 throw new \Exception ($ errstr );
124147 });
@@ -151,6 +174,9 @@ static public function release($key)
151174 $ keyMD5 = md5 (self ::$ keyPrefix . serialize ($ key ));
152175 if (!isset (self ::$ data [$ keyMD5 ])) {
153176 throw new \Exception ('A lock name " ' . $ key . '" does not exists in current process! ' );
177+ }
178+ $ dir = self ::getLocksDir ();
179+ if (!is_dir ($ dir )) {
154180 return ;
155181 }
156182 set_error_handler (function ($ errno , $ errstr ) {
@@ -159,7 +185,7 @@ static public function release($key)
159185 try {
160186 if (flock (self ::$ data [$ keyMD5 ], LOCK_UN ) && fclose (self ::$ data [$ keyMD5 ])) {
161187 try {
162- $ filename = self :: getLocksDir () . $ keyMD5 . '.lock ' ;
188+ $ filename = $ dir . $ keyMD5 . '.lock ' ;
163189 $ tempFilename = $ filename . '. ' . md5 (uniqid () . rand (0 , 999999 ));
164190 $ renameResult = rename ($ filename , $ tempFilename );
165191 if ($ renameResult ) {
0 commit comments