2022-03-08 23:38:57 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace NoccyLabs\FreshDocker\State;
|
|
|
|
|
|
|
|
class Lockfile
|
|
|
|
{
|
|
|
|
private string $filename;
|
|
|
|
|
|
|
|
private int $maxLock = 3600;
|
|
|
|
|
2022-07-05 20:46:11 +00:00
|
|
|
private bool $locked = false;
|
|
|
|
|
2022-03-08 23:38:57 +00:00
|
|
|
public function __construct(string $filename)
|
|
|
|
{
|
|
|
|
$this->filename = $filename;
|
|
|
|
register_shutdown_function([$this,"release"]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function lock()
|
|
|
|
{
|
|
|
|
if (file_exists($this->filename)) {
|
2022-03-11 00:55:35 +00:00
|
|
|
if (time() - filemtime($this->filename) < $this->maxLock) {
|
2022-03-08 23:38:57 +00:00
|
|
|
throw new \RuntimeException("Lockfile {$this->filename} already exists");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
touch($this->filename);
|
2022-07-05 20:46:11 +00:00
|
|
|
$this->locked = true;
|
2022-03-08 23:38:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function release()
|
|
|
|
{
|
2022-07-05 20:46:11 +00:00
|
|
|
if ($this->locked && file_exists($this->filename)) {
|
2022-03-08 23:38:57 +00:00
|
|
|
unlink($this->filename);
|
|
|
|
}
|
2022-07-05 20:46:11 +00:00
|
|
|
$this->locked = false;
|
2022-03-08 23:38:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-07-05 20:46:11 +00:00
|
|
|
}
|