116 lines
2.4 KiB
PHP
116 lines
2.4 KiB
PHP
<?php
|
|
|
|
// src/Utils\Configuration/ConfigurationService.php
|
|
|
|
namespace RprtCli\Utils\Configuration;
|
|
|
|
use RprtCli\Utils\Configuration\ConfigurationInterface;
|
|
use Symfony\Component\Yaml\Yaml;
|
|
|
|
/**
|
|
* Read and write configuration.
|
|
*
|
|
* Check:
|
|
* - $HOME/.rprt.config.yaml
|
|
* - $HOME/.rprt/rprt.config.yaml
|
|
* - $HOME/.config/rprt-cli/rprt.config.yaml
|
|
*/
|
|
class ConfigurationService implements ConfigurationInterface
|
|
{
|
|
|
|
const PATHS = [
|
|
'/.',
|
|
'/.config/rprt-cli/',
|
|
'/.rprt/',
|
|
];
|
|
|
|
protected $data;
|
|
|
|
protected $default = null;
|
|
|
|
protected $configFilePath;
|
|
|
|
protected $configFileName;
|
|
|
|
/**
|
|
* Yaml service.
|
|
*
|
|
* @var \Symfony\Component\Yaml\Yaml::parseFile;
|
|
*/
|
|
protected $yamlParseFile;
|
|
|
|
/**
|
|
* Construct method.
|
|
*/
|
|
function __construct(string $filepath, string $filename) {
|
|
$file = $filepath . $filename;
|
|
$this->configFileName = $filename;
|
|
$this->configFilePath = $this->findConfig($file);
|
|
if ($this->configFilePath) {
|
|
$this->getConfig();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Checks for config file.
|
|
*
|
|
* @return string|bool
|
|
* Full path to config file or FALSE if it doesn't exist.
|
|
*/
|
|
public function findConfig($filename) {
|
|
if (file_exists($filename)) {
|
|
return $filename;
|
|
}
|
|
foreach (self::PATHS as $path) {
|
|
$fullPath = $_SERVER['HOME'] . $path . $this->configFileName;
|
|
if (file_exists($fullPath)) {
|
|
return $fullPath;
|
|
}
|
|
}
|
|
// @TODO This should be some kind of error!
|
|
var_dump('Config File Not Found!');
|
|
return FALSE;
|
|
}
|
|
|
|
/**
|
|
* Get and read the configuration from file.
|
|
*/
|
|
public function getConfig() {
|
|
if ($this->configFilePath) {
|
|
$config = Yaml::parseFile($this->configFilePath);
|
|
$this->data = $config;
|
|
return TRUE;
|
|
}
|
|
// Maybe write an exception for missing config.
|
|
// Ask for reconfiguration.
|
|
// @TODO This should be some kind of error!
|
|
var_dump('Config File Path not found!');
|
|
return FALSE;
|
|
}
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function get($key, $default = null) {
|
|
$this->default = $default;
|
|
$segments = explode('.', $key);
|
|
$data = $this->data;
|
|
foreach ($segments as $segment) {
|
|
if (isset($data[$segment])) {
|
|
$data = $data[$segment];
|
|
} else {
|
|
$data = $this->default;
|
|
break;
|
|
}
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function exists($key) {
|
|
return $this->get($key) !== $this->default;
|
|
}
|
|
}
|