Skip to content

Instantly share code, notes, and snippets.

@ivanche
Created November 7, 2017 13:13
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 ivanche/6b6b60d407e4e6b43c012524ddf05360 to your computer and use it in GitHub Desktop.
Save ivanche/6b6b60d407e4e6b43c012524ddf05360 to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Service;
class Locker
{
protected $baseDir;
public function __construct($dir)
{
$this->baseDir = $dir;
}
public function acquireLock($file)
{
$filename = $this->baseDir . DIRECTORY_SEPARATOR . $file;
if (!$this->isLocked($file)) {
file_put_contents($filename, ((new \DateTime('now'))->format(\DateTime::ATOM)));
chmod($filename, 0777); // if the file cant be opened for writing later, getting the lock will fail
}
}
public function releaseLock($file)
{
$filename = $this->baseDir . DIRECTORY_SEPARATOR . $file;
if ($this->isLocked($file)) {
unlink($filename);
}
}
public function isLocked($file)
{
return file_exists($this->baseDir . DIRECTORY_SEPARATOR . $file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment