Created
November 7, 2017 13:13
-
-
Save ivanche/6b6b60d407e4e6b43c012524ddf05360 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 | |
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