Configuration refactoring with schema support.
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
2023-07-04 09:43:27 +00:00
parent 006a5410b5
commit 51f8436e9d
5 changed files with 358 additions and 17 deletions

View File

@ -7,6 +7,8 @@ use Symfony\Component\Yaml\Exception\ParseException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Psr\Log\NullLogger;
use League\Config\Configuration;
use Nette\Schema\Expect;
/**
* Application class
@ -15,25 +17,56 @@ use Psr\Log\NullLogger;
*
* @author Jens True <jens.chr.true@gmail.com>
* @license https://opensource.org/licenses/gpl-license.php GNU Public License
* @link https://jcktrue.dks
* @link https://jcktrue.dk
*/
class App
{
protected Logger $logger;
protected mixed $config;
protected Configuration $config;
/**
* Create a new instance providing a config file
*
* @param string $configFile Relative or full path to YML config.
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function __construct(string $configFile)
{
// Define your configuration schema
$this->config = new Configuration([
'rclone' => Expect::structure([
'path' => Expect::string()->default('rclone'),
'options' => Expect::arrayOf('string', 'string')
]),
'backup' => Expect::arrayOf(Expect::structure([
'title' => Expect::string(),
'source' => Expect::string(),
'destination' => Expect::string(),
])),
'notification' => Expect::arrayOf(Expect::structure([
'type' => Expect::string(),
'domain' => Expect::string(),
'topic' => Expect::string(),
])),
'log' => Expect::string()->assert(
function (string $path): bool {
return is_writable($path);
}
)->required(),
'templates' => Expect::structure(['notify' => Expect::string()])
]);
$parser = new Yaml();
$this->config = $parser->parseFile($configFile);
$parsedConfig = $parser->parseFile($configFile);
// Merge those values into your configuration schema:
$this->config->merge($parsedConfig);
$logger = new Logger('app');
if (isset($this->config['log'])) {
$logger->pushHandler(new StreamHandler($this->getConfig()['log']));
if ($this->config->get('log')) {
$logger->pushHandler(new StreamHandler($this->config->get('log')));
}
$logger->info("Initialization complete");
@ -41,13 +74,14 @@ class App
}
/**
* Get the full configuration
* Get configuration from key
*
* @return mixed Full configuration structure
* @param non-empty-string $key Key to fetch
* @return mixed Configuration value
*/
public function getConfig(): mixed
public function getConfig(string $key): mixed
{
return $this->config;
return $this->config->get($key);
}
/**