ytkns/src/Config.php
2021-07-28 20:52:46 +00:00

57 lines
1.7 KiB
PHP

<?php
namespace YTKNS;
final class Config {
public const TYPE_ANY = '';
public const TYPE_STR = 'string';
public const TYPE_INT = 'integer';
public const TYPE_BOOL = 'boolean';
public const TYPE_ARR = 'array';
public const DEFAULTS = [
self::TYPE_ANY => null,
self::TYPE_STR => '',
self::TYPE_INT => 0,
self::TYPE_BOOL => false,
self::TYPE_ARR => [],
];
private static array $config = [];
public static function init(): void {
$raw = DB::prepare('SELECT `config_key`, `config_value` FROM `ytkns_config`');
$raw->execute();
$raw = $raw->fetchAll();
foreach($raw as $entry)
self::$config[$entry['config_key']] = unserialize($entry['config_value']);
}
public static function get(string $key, string $type = self::TYPE_ANY, $default = null) {
$value = self::$config[$key] ?? null;
if($type !== self::TYPE_ANY && gettype($value) !== $type)
$value = null;
return $value ?? $default ?? self::DEFAULTS[$type];
}
public static function set(string $key, $value, bool $soft = false): void {
self::$config[$key] = $value;
if(!YTKNS_MAINTENANCE && !$soft) {
$value = serialize($value);
$save = DB::prepare('REPLACE INTO `ytkns_config` (`config_key`, `config_value`) VALUES (:key, :value)');
$save->bindValue('key', $key);
$save->bindValue('value', $value);
$save->execute();
}
}
public static function setDefault(string $key, $value, bool $soft = false): void {
if($value !== null && self::get($key) === null)
self::set($key, $value, $soft);
}
}