Initial commit
This commit is contained in:
47
src/State/PersistentState.php
Normal file
47
src/State/PersistentState.php
Normal file
@ -0,0 +1,47 @@
|
||||
<?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;
|
||||
register_shutdown_function([$this,"flush"]);
|
||||
if (file_exists($filename)) {
|
||||
$this->state = Yaml::parseFile($filename);
|
||||
}
|
||||
}
|
||||
|
||||
public function flush()
|
||||
{
|
||||
if (!$this->dirty) return;
|
||||
$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]);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user