subcon.town/libs/zap/Config/Repository.php

66 lines
1.8 KiB
PHP

<?php
namespace Subcon\Zap\Config;
use Subcon\Zap\Application;
class Repository
{
protected array $items;
public function __construct(Application $app)
{
//Load from cache if it exists
if($this->loadFromCache(realpath($app->getBasePath('cache')))) {
return;
}
//Otherwise, load from config files
$this->loadConfigurationFiles(realpath($app->getBasePath('config')));
}
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;
}
public function buildCache()
{
}
protected function loadFromCache(string $cachePath): bool
{
if(!file_exists($cachePath) || !file_exists($cachePath . DIRECTORY_SEPARATOR . 'config-cache.php')) {
return false;
}
$this->items = require $cachePath . DIRECTORY_SEPARATOR . 'config-cache.php';
return true;
}
protected function loadConfigurationFiles(string $configPath)
{
$files = glob($configPath . DIRECTORY_SEPARATOR . '*.php');
if($files === false || empty($files)) {
throw new \RuntimeException('Unable to load configuration, no configuration files found.');
} elseif(!in_array($configPath . 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;
$this->items = array_merge($this->items, $items);
}
}
}