37 lines
964 B
PHP
37 lines
964 B
PHP
<?php
|
|
|
|
class Storage
|
|
{
|
|
private string $dir;
|
|
|
|
public function __construct(string $dir)
|
|
{
|
|
$this->dir = rtrim($dir, DIRECTORY_SEPARATOR);
|
|
if (!is_dir($this->dir)) {
|
|
mkdir($this->dir, 0777, true);
|
|
}
|
|
if (!is_writable($this->dir)) {
|
|
throw new RuntimeException('Storage path not writable: ' . $this->dir);
|
|
}
|
|
}
|
|
|
|
private function path(string $name): string
|
|
{
|
|
return $this->dir . DIRECTORY_SEPARATOR . $name . '.json';
|
|
}
|
|
|
|
public function get(string $name, $default = [])
|
|
{
|
|
$p = $this->path($name);
|
|
if (!file_exists($p)) return $default;
|
|
$data = json_decode((string)file_get_contents($p), true);
|
|
return $data ?? $default;
|
|
}
|
|
|
|
public function set(string $name, $value): void
|
|
{
|
|
$p = $this->path($name);
|
|
file_put_contents($p, json_encode($value, JSON_PRETTY_PRINT));
|
|
}
|
|
}
|