rosavox/source/logic.php

173 lines
2.5 KiB
PHP
Raw Normal View History

2025-05-21 06:05:12 +00:00
<?php
namespace rosavox\logic;
require_once(__DIR__ . '/helpers.php');
/**
*/
class docs_state
{
public static int $current_id = 0;
/**
* @param array {record<string,array>}
*/
public static array $pool = [];
}
2025-05-21 16:54:14 +00:00
/**
*/
function docs_push() : void
{
$path = 'docs.json';
$data = [
'current_id' => docs_state::$current_id,
'pool' => docs_state::$pool,
];
$content = \json_encode($data, \JSON_PRETTY_PRINT);
\file_put_contents($path, $content);
}
/**
*/
function docs_pull() : void
{
$path = 'docs.json';
$content = (\file_exists($path) ? \file_get_contents($path) : null);
$data = (
($content === null)
?
['current_id' => 0, 'pool' => []]
:
\json_decode($content, true)
);
docs_state::$current_id = $data['current_id'];
docs_state::$pool = $data['pool'];
}
2025-05-21 06:05:12 +00:00
/**
*/
function docs_id_encode(int $id) : string
{
return \sprintf('%u', $id);
}
/**
*/
function docs_id_decode(string $id_encoded) : int
{
return intval($id_encoded);
}
/**
*/
function docs_list() : array
{
return \array_map(
fn ($id_encoded) => [
'id' => docs_id_decode($id_encoded),
'doc' => docs_state::$pool[$id_encoded],
],
\array_keys(docs_state::$pool)
);
}
/**
*/
function docs_read(int $id) : array
{
$id_encoded = docs_id_encode($id);
if (! \array_key_exists($id_encoded, docs_state::$pool))
{
2025-05-21 16:54:14 +00:00
throw (new \Exception('not found'));
2025-05-21 06:05:12 +00:00
}
else
{
return docs_state::$pool[$id_encoded];
}
}
/**
*/
function docs_create(array $doc) : int
{
docs_state::$current_id += 1;
$id = docs_state::$current_id;
$id_encoded = docs_id_encode($id);
docs_state::$pool[$id_encoded] = $doc;
2025-05-21 16:54:14 +00:00
docs_push();
2025-05-21 06:05:12 +00:00
return $id;
}
/**
*/
function docs_update(int $id, array $doc) : void
{
$id_encoded = docs_id_encode($id);
if (! \array_key_exists($id_encoded, docs_state::$pool))
{
2025-05-21 16:54:14 +00:00
throw (new \Exception('not found'));
2025-05-21 06:05:12 +00:00
}
else
{
docs_state::$pool[$id_encoded] = $doc;
2025-05-21 16:54:14 +00:00
docs_push();
2025-05-21 06:05:12 +00:00
}
}
/**
*/
function docs_delete(int $id) : void
{
$id_encoded = docs_id_encode($id);
if (! \array_key_exists($id_encoded, docs_state::$pool))
{
2025-05-21 16:54:14 +00:00
throw (new \Exception('not found'));
2025-05-21 06:05:12 +00:00
}
else
{
docs_state::$pool[$id_encoded] = null;
unset(docs_state::$pool[$id_encoded]);
2025-05-21 16:54:14 +00:00
docs_push();
2025-05-21 06:05:12 +00:00
}
}
2025-05-21 16:54:14 +00:00
/**
*/
function docs_init() : void
{
docs_pull();
}
2025-05-21 06:05:12 +00:00
/**
*/
function docs_add_examples() : void
{
docs_create(
[
'title' => 'Freibier bei Parteitagen',
'authors' => [
'Björn Biernot',
'Doreen Dauerdurst',
],
'content' => 'Wir haben Durst!',
'reasoning' => null,
]
);
}
?>