AntCMS/src/AntCMS/AntConfig.php

97 lines
2.4 KiB
PHP
Raw Normal View History

2023-01-06 22:17:33 +00:00
<?php
namespace AntCMS;
use AntCMS\AntYaml;
use Exception;
2023-01-06 22:17:33 +00:00
class AntConfig
{
private static $ConfigKeys = [
'siteInfo',
'forceHTTPS',
'activeTheme',
'enableCache',
'admin',
'debug',
'baseURL',
];
2023-01-11 01:24:30 +00:00
/**
* Generates the default config file and saves it.
* @return void
*/
2023-01-06 22:17:33 +00:00
public static function generateConfig()
{
$defaultOptions = [
'siteInfo' => [
'siteTitle' => 'AntCMS',
],
2023-01-06 22:17:33 +00:00
'forceHTTPS' => true,
2023-01-07 09:28:04 +00:00
'activeTheme' => 'Default',
2023-01-06 22:17:33 +00:00
'enableCache' => true,
'admin' => array(
'username' => 'Admin',
2023-01-06 22:17:33 +00:00
'password' => '',
),
'debug' => true,
2023-01-07 01:09:55 +00:00
'baseURL' => $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']),
];
2023-01-06 22:17:33 +00:00
Self::saveConfig($defaultOptions);
2023-01-06 22:17:33 +00:00
}
2023-01-11 01:24:30 +00:00
/**
* Retrieves the current configuration from the AntCMS config file.
*
* @param string|null $key The key of the configuration item to retrieve. Use dot notation to specify nested keys.
* @return mixed The configuration array or a specific value if the key is specified.
*/
public static function currentConfig(?string $key = null)
2023-01-06 22:17:33 +00:00
{
2023-01-11 01:24:30 +00:00
$config = AntYaml::parseFile(antConfigFile);
if (is_null($key)) {
return $config;
} else {
$keys = explode('.', $key);
return self::getArrayValue($config, $keys);
}
2023-01-06 22:17:33 +00:00
}
2023-01-11 01:24:30 +00:00
/**
* @param array<mixed> $array
* @param array<mixed> $keys
* @return mixed
*/
private static function getArrayValue(array $array, array $keys)
2023-01-11 01:24:30 +00:00
{
foreach ($keys as $key) {
if (isset($array[$key])) {
$array = $array[$key];
2023-01-11 01:24:30 +00:00
} else {
return null;
}
}
2023-01-11 01:24:30 +00:00
return $array;
}
/**
* Saves the AntCMS configuration
*
* @param array<mixed> $config The config data to be saved.
* @return bool
* @throws exception
2023-01-11 01:24:30 +00:00
*/
public static function saveConfig(array $config)
2023-01-06 22:17:33 +00:00
{
foreach (self::$ConfigKeys as $defaultKey) {
if (!array_key_exists($defaultKey, $config)) {
throw new Exception("New config is missing the required {$defaultKey} key from it's array!");
}
}
return AntYaml::saveFile(antConfigFile, $config);
2023-01-06 22:17:33 +00:00
}
}