Files
backupscript/src/App.php

109 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App;
use Symfony\Component\Yaml\Yaml;
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;
/**
* Mostly working as a register pattern for the logging and configuration.
*/
final class App
{
/// Logging instance
protected Logger $logger;
/// Configuration singleton
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()->required(),
'source' => Expect::string()->required(),
'destination' => Expect::string()->required(),
]))->required(),
'notification' => Expect::arrayOf(Expect::structure([
'type' => Expect::string()->required(),
'domain' => Expect::string()->required(),
'topic' => Expect::string()->required(),
])),
'log' => Expect::string()->assert(
function (string $path): bool {
return touch($path);
}
),
'templates' => Expect::structure(
[
'notify' => Expect::string()->required(),
'error' => Expect::string()->required()
]
)->required()
]);
$parser = new Yaml();
/**
* @var array<string, mixed>
*/
$parsedConfig = $parser->parseFile($configFile);
// Merge those values into the configuration schema:
$this->config->merge($parsedConfig);
$logger = new Logger('app');
if ($this->config->get('log')) {
$logger->pushHandler(new StreamHandler((string)$this->config->get('log')));
$logger->info("Logging enabled");
}
$logger->info("Initialization complete");
$this->logger = $logger;
}
/**
* Get configuration from key
*
* @param non-empty-string $key Key to fetch
*
* @return mixed Configuration value
*/
public function getConfig(string $key): mixed
{
/**
* @var string|array<string, string>
*/
$ret = $this->config->get($key);
$this->logger->debug("Fetching configuration key", [$key, $ret]);
return $ret;
}
/**
* Get the logger instance.
*
* @return Logger Instance of logger
*/
public function getLogger(): Logger
{
return $this->logger;
}
}