Christopher Vagnetoft
ec1659e96d
* Moved logic from entrypoint to a dedicated class. * Disabled automatic flush of state. * Added locking support to prevent multiple instances. * Added logging * Added base interface for CredentialsLoader
49 lines
1.0 KiB
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]);
|
|
}
|
|
} |