2022-03-07 21:45:54 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace NoccyLabs\FreshDocker\State;
|
|
|
|
|
|
|
|
use Symfony\Component\Yaml\Yaml;
|
|
|
|
|
|
|
|
class PersistentState
|
|
|
|
{
|
|
|
|
private string $filename;
|
|
|
|
|
|
|
|
private array $state = [];
|
|
|
|
|
|
|
|
private bool $dirty = false;
|
|
|
|
|
|
|
|
public function __construct(string $filename)
|
|
|
|
{
|
|
|
|
$this->filename = $filename;
|
2022-03-08 23:38:57 +00:00
|
|
|
// register_shutdown_function([$this,"flush"]);
|
2022-03-07 21:45:54 +00:00
|
|
|
if (file_exists($filename)) {
|
2022-03-08 23:38:57 +00:00
|
|
|
$this->state = Yaml::parseFile($filename) ?? [];
|
2022-03-07 21:45:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function flush()
|
|
|
|
{
|
|
|
|
if (!$this->dirty) return;
|
2022-03-08 23:38:57 +00:00
|
|
|
$this->dirty = false;
|
|
|
|
|
2022-03-07 21:45:54 +00:00
|
|
|
$yaml = Yaml::dump($this->state);
|
|
|
|
file_put_contents($this->filename."~", $yaml);
|
|
|
|
rename($this->filename."~", $this->filename);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function set(string $key, $value)
|
|
|
|
{
|
|
|
|
$this->state[$key] = $value;
|
|
|
|
$this->dirty = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function get(string $key, $default=null): mixed
|
|
|
|
{
|
|
|
|
return $this->state[$key] ?? $default;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function unset(string $key)
|
|
|
|
{
|
|
|
|
unset($this->state[$key]);
|
|
|
|
}
|
|
|
|
}
|