| 1 | <?php |
||
| 17 | class FileLock implements LockInterface |
||
| 18 | { |
||
| 19 | /** |
||
| 20 | * @var string lock file |
||
| 21 | */ |
||
| 22 | protected $file; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @var resource |
||
| 26 | */ |
||
| 27 | protected $fp; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @var bool |
||
| 31 | */ |
||
| 32 | protected $locked = false; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @param $file |
||
| 36 | */ |
||
| 37 | 12 | private function __construct($file) |
|
| 38 | { |
||
| 39 | 12 | if (!file_exists($file) || !is_readable($file)) { |
|
| 40 | throw new \RuntimeException("{$file} is not exists or not readable"); |
||
| 41 | } |
||
| 42 | 12 | $this->fp = fopen($file, "r+"); |
|
| 43 | 12 | if (!is_resource($this->fp)) { |
|
| 44 | throw new \RuntimeException("open {$file} failed"); |
||
| 45 | } |
||
| 46 | 12 | } |
|
| 47 | |||
| 48 | /** |
||
| 49 | * create a file lock instance |
||
| 50 | * if the file is not exists, it will be created |
||
| 51 | * |
||
| 52 | * @param string $file lock file |
||
| 53 | * @return FileLock |
||
| 54 | */ |
||
| 55 | 12 | public static function create($file) |
|
| 56 | { |
||
| 57 | 12 | return new FileLock($file); |
|
| 58 | } |
||
| 59 | |||
| 60 | /** |
||
| 61 | * get a lock |
||
| 62 | * |
||
| 63 | * @param bool $blocking |
||
| 64 | * @return mixed |
||
| 65 | */ |
||
| 66 | 9 | public function acquire($blocking = true) |
|
| 85 | |||
| 86 | /** |
||
| 87 | * is locked |
||
| 88 | * |
||
| 89 | * @return mixed |
||
| 90 | */ |
||
| 91 | public function isLocked() |
||
| 95 | |||
| 96 | /** |
||
| 97 | * |
||
| 98 | */ |
||
| 99 | public function __destory() |
||
| 105 | |||
| 106 | /** |
||
| 107 | * release lock |
||
| 108 | * |
||
| 109 | * @return mixed |
||
| 110 | */ |
||
| 111 | 9 | public function release() |
|
| 126 | } |