forked from mikehaertl/packagecompressor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEMutex.php
91 lines (75 loc) · 2.45 KB
/
EMutex.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
<?php
/**
* EMutex
*
* This is the mutex extension V1.10 available here:
* http://www.yiiframework.com/extension/mutex
*
* (Tabs replaced by spaces + empty lines removed)
*/
class EMutex extends CApplicationComponent
{
public $mutexFile;
private $_locks = array();
public function init()
{
parent::init();
if (null === $this->mutexFile)
{
$this->mutexFile = Yii::app()->getRuntimePath() . '/mutex.bin';
}
}
public function lock($id, $timeout = 0)
{
$lockFileHandle = $this->_getLockFileHandle($id);
if (flock($lockFileHandle, LOCK_EX))
{
$data = @unserialize(@file_get_contents($this->mutexFile));
if (empty($data))
{
$data = array();
}
if (!isset($data[$id]) || ($data[$id][0] > 0 && $data[$id][0] + $data[$id][1] <= microtime(true)))
{
$data[$id] = array($timeout, microtime(true));
array_push($this->_locks, $id);
$result = (bool)file_put_contents($this->mutexFile, serialize($data));
}
}
fclose($lockFileHandle);
@unlink($this->_getLockFile($id));
return isset($result) ? $result : false;
}
public function unlock($id = null)
{
if (null === $id && null === ($id = array_pop($this->_locks)))
{
throw new CException("No lock available that could be released. Make sure to setup a lock first.");
}
elseif (in_array($id, $this->_locks))
{
throw new CException("Don't define the id for a local lock. Only do it for locks that weren't created within the current request.");
}
$lockFileHandle = $this->_getLockFileHandle($id);
if (flock($lockFileHandle, LOCK_EX))
{
$data = @unserialize(@file_get_contents($this->mutexFile));
if (!empty($data) && isset($data[$id]))
{
unset($data[$id]);
$result = (bool)file_put_contents($this->mutexFile, serialize($data));
}
}
fclose($lockFileHandle);
@unlink($this->_getLockFile($id));
return isset($result) ? $result : false;
}
private function _getLockFile($id)
{
return "{$this->mutexFile}." . md5($id) . '.lock';
}
private function _getLockFileHandle($id)
{
return fopen($this->_getLockFile($id), 'a+b');
}
}