Stop using a singleton for Config (#298)

This commit is contained in:
Pierre Rudloff 2020-10-17 22:07:07 +02:00
parent 6fc294afbe
commit 7e2afd8221
14 changed files with 87 additions and 169 deletions

View file

@ -20,12 +20,6 @@ use Jawira\CaseConverter\Convert;
*/
class Config
{
/**
* Singleton instance.
*
* @var Config|null
*/
private static $instance;
/**
* youtube-dl binary path.
@ -160,10 +154,11 @@ class Config
* @param mixed[] $options Options
* @throws ConfigException
*/
private function __construct(array $options = [])
public function __construct(array $options = [])
{
$this->applyOptions($options);
$this->getEnv();
$this->validateOptions();
$localeManager = LocaleManager::getInstance();
if (empty($this->genericFormats)) {
@ -271,34 +266,17 @@ class Config
}
}
/**
* Get Config singleton instance.
*
* @return Config
* @todo Stop using a singleton.
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Set options from a YAML file.
*
* @param string $file Path to the YAML file
* @return void
* @return Config
* @throws ConfigException
*/
public static function setFile(string $file)
public static function fromFile(string $file)
{
if (is_file($file)) {
$options = Yaml::parse(strval(file_get_contents($file)));
self::$instance = new self($options);
self::$instance->validateOptions();
return new self(Yaml::parse(strval(file_get_contents($file))));
} else {
throw new ConfigException("Can't find config file at " . $file);
}
@ -308,29 +286,13 @@ class Config
* Manually set some options.
*
* @param mixed[] $options Options (see `config/config.example.yml` for available options)
* @param bool $update True to update an existing instance
* @return void
* @throws ConfigException
*/
public static function setOptions(array $options, $update = true)
public function setOptions(array $options)
{
if ($update) {
$config = self::getInstance();
$config->applyOptions($options);
$config->validateOptions();
} else {
self::$instance = new self($options);
}
}
/**
* Destroy singleton instance.
*
* @return void
*/
public static function destroyInstance()
{
self::$instance = null;
$this->applyOptions($options);
$this->validateOptions();
}
/**

View file

@ -19,10 +19,10 @@ class ConfigFactory
{
$configPath = __DIR__ . '/../config/config.yml';
if (is_file($configPath)) {
Config::setFile($configPath);
$config = Config::fromFile($configPath);
} else {
$config = new Config();
}
$config = Config::getInstance();
if ($config->uglyUrls) {
$container['router'] = new UglyRouter();
}