zappy-base/src/Config/ConfigRepository.php
2024-05-19 15:45:12 +02:00

66 lines
1.9 KiB
PHP

<?php
namespace Musoka\Zap\Config;
class ConfigRepository
{
protected array $items;
public function __construct(string $configDirPath, string $cacheDirPath)
{
//Load from cache if it exists
if($this->loadFromCache($cacheDirPath)) {
return;
}
//Otherwise, load from config files
$this->loadConfigurationFiles($configDirPath);
}
public function get(string $key, $default = null)
{
$keys = explode('.', $key);
$value = $this->items;
foreach($keys as $index) {
if(!key_exists($index, $value)) return $default;
$value = $value[$index];
}
return $value;
}
protected function loadFromCache(string $cacheDirPath): bool
{
if(!file_exists($cacheDirPath) || !file_exists($cacheDirPath . DIRECTORY_SEPARATOR . 'config-cache.php')) {
return false;
}
$this->items = require $cacheDirPath . DIRECTORY_SEPARATOR . 'config-cache.php';
return true;
}
protected function loadConfigurationFiles(string $configDirPath)
{
$files = glob($configDirPath . DIRECTORY_SEPARATOR . '*.php');
if($files === false || empty($files)) {
throw new \RuntimeException('Unable to load configuration, no configuration files found.');
} elseif(!in_array($configDirPath . DIRECTORY_SEPARATOR . 'application.php', $files)) {
throw new \RuntimeException('Unable to load the application configuration, app configuration file is missing.');
}
$this->items = [];
foreach($files as $file) {
$items = require $file;
$key = basename($file, '.php');
$this->items[$key] = $items;
//$this->items = array_merge($this->items, $items);
}
}
protected function writeToCache()
{
// TODO: Write caching function for configuration
}
}