Implement stow config file and folder unwrapping
Move includes to their own folder, config.php will otherwise be included and cleans up nicely
This commit is contained in:
71
php/includes/config.php
Normal file
71
php/includes/config.php
Normal file
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/functions.php';
|
||||
|
||||
readonly class homeConfig extends config
|
||||
{
|
||||
private const CONFIG_BASE_PATH = '.config';
|
||||
|
||||
public function __construct(
|
||||
string $name
|
||||
)
|
||||
{
|
||||
parent::__construct(path(
|
||||
getenv('HOME'),
|
||||
self::CONFIG_BASE_PATH,
|
||||
$name
|
||||
));
|
||||
$this->createConfig();
|
||||
}
|
||||
|
||||
private function createConfig(): void
|
||||
{
|
||||
if (file_exists($this->getConfigFile())) {
|
||||
return;
|
||||
} else {
|
||||
if (!is_dir($this->getConfigPath())) {
|
||||
mkdir($this->getConfigPath(), 0755, true);
|
||||
}
|
||||
$this->writeConfig([]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
readonly class config
|
||||
{
|
||||
public function __construct(
|
||||
private string $path,
|
||||
private string $fileName = 'config.php',
|
||||
) {}
|
||||
|
||||
public function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!file_exists($this->getConfigFile())) {
|
||||
return $default;
|
||||
}
|
||||
$config = include $this->getConfigFile();
|
||||
return $config[$key] ?? $default;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value): void
|
||||
{
|
||||
$config = include $this->getConfigFile();
|
||||
$config[$key] = $value;
|
||||
$this->writeConfig($config);
|
||||
}
|
||||
|
||||
protected function getConfigFile(): string
|
||||
{
|
||||
return path($this->getConfigPath(), $this->fileName);
|
||||
}
|
||||
|
||||
protected function getConfigPath(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
protected function writeConfig(array $config): void
|
||||
{
|
||||
file_put_contents($this->getConfigFile(), '<?php return ' . var_export($config, true) . ';');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user