fresh/src/State/PersistentState.php

49 lines
1.0 KiB
PHP

<?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;
$this->dirty = false;
$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]);
}
}