Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayleedev/9772292 to your computer and use it in GitHub Desktop.
Save bayleedev/9772292 to your computer and use it in GitHub Desktop.
<?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