Add includes/jsondb.php
This commit is contained in:
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
class JsonDB
|
||||||
|
{
|
||||||
|
public static function read(string $file): array
|
||||||
|
{
|
||||||
|
if (!file_exists($file)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$json = file_get_contents($file);
|
||||||
|
|
||||||
|
if (!$json) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return json_decode($json, true) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function write(
|
||||||
|
string $file,
|
||||||
|
array $data
|
||||||
|
): bool {
|
||||||
|
|
||||||
|
$dir = dirname($file);
|
||||||
|
|
||||||
|
if (!is_dir($dir)) {
|
||||||
|
mkdir($dir, 0775, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
$fp = fopen($file, 'c+');
|
||||||
|
|
||||||
|
if (!$fp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
flock($fp, LOCK_EX);
|
||||||
|
|
||||||
|
ftruncate($fp, 0);
|
||||||
|
|
||||||
|
fwrite(
|
||||||
|
$fp,
|
||||||
|
json_encode(
|
||||||
|
$data,
|
||||||
|
JSON_PRETTY_PRINT |
|
||||||
|
JSON_UNESCAPED_UNICODE
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
fflush($fp);
|
||||||
|
|
||||||
|
flock($fp, LOCK_UN);
|
||||||
|
|
||||||
|
fclose($fp);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user