Last active
August 29, 2015 13:57
-
-
Save bayleedev/9772292 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This has the same interface as the previous FileLock but supports multiple locks. | |
* This allows you to run x processes at the same time. | |
*/ | |
class FileLock { | |
public $lockFile = null; | |
public $config = array(); | |
public function __construct($config = array()) { | |
$this->config = $config + array( | |
'format' => 'file{:num}.lock', | |
'file' => null, | |
'max' => 5, | |
); | |
} | |
public function __destruct() { | |
$this->cleanup(); | |
} | |
public function lock() { | |
$this->lockFile = $this->findEmptyLock(); | |
file_put_contents($this->lockFile, time()); | |
} | |
public function unlock() { | |
$this->lockFile && unlink($this->lockFile); | |
} | |
/** | |
* You are only locked if all potential lock files exist. | |
*/ | |
public function isLocked() { | |
return !$this->findEmptyLock(); | |
} | |
protected function findEmptyLock() { | |
return $this->iterateLocks(function($lock) { | |
if (!file_exists($lock)) { | |
return $lock; | |
} | |
return false; | |
}); | |
} | |
/** | |
* Will allow you to iterate all the potential lock files. | |
* The first `trueish` value returns breaks the iteration cycle. | |
* | |
* @return mixed The trueish value the callback returns or `false`. | |
*/ | |
protected function iterateLocks($callback) { | |
$max = $this->config['max']; | |
$format = $this->config['format']; | |
for ($i = 0; $i<$max;$i++) { | |
if ($value = $callback(str_replace('{:num}', $i, $format))) { | |
return $value; | |
} | |
} | |
return false; | |
} | |
/** | |
* Clean's up dead lock files. | |
* | |
* @param int $age The max age of a lock file. | |
* @return bool True | |
*/ | |
public function cleanup($age = 600) { | |
$this->iterateLocks(function($lock) { | |
$time = file_exists($lock) ? (int) file_get_contents($lock) : time(); | |
if ($time + $age < time()) { | |
unlink($lock); | |
} | |
}); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment