changing Config to silently ignore read errors by default

The old behavior is still available by setting public property $strict to true
This commit is contained in:
Joby 2020-06-18 10:34:44 -06:00
parent 1f1980ba23
commit d311c5b1c8

View file

@ -2,12 +2,13 @@
/* Flatrr | https://gitlab.com/byjoby/flatrr | MIT License */
namespace Flatrr\Config;
use Symfony\Component\Yaml\Yaml;
use Flatrr\SelfReferencingFlatArray;
use Flatrr\FlatArray;
use Symfony\Component\Yaml\Yaml;
class Config extends SelfReferencingFlatArray implements ConfigInterface
{
public $strict = false;
public function readDir($dir, string $name = null, bool $overwrite = null)
{
$dir = realpath($dir);
@ -29,7 +30,11 @@ class Config extends SelfReferencingFlatArray implements ConfigInterface
{
$fn = 'parse_' . $format;
if (!method_exists($this, $fn)) {
if ($this->strict) {
throw new \Exception("Don't know how to parse the format \"$format\"");
} else {
return null;
}
}
if ($out = $this->$fn($input)) {
return $out;
@ -75,16 +80,28 @@ class Config extends SelfReferencingFlatArray implements ConfigInterface
public function readFile($filename, string $name = null, bool $overwrite = false)
{
if (!is_file($filename) || !is_readable($filename)) {
if ($this->strict) {
throw new \Exception("Couldn't read config file \"$filename\"");
} else {
return null;
}
}
$format = strtolower(preg_replace('/.+\./', '', $filename));
$fn = 'read_' . $format;
if (!method_exists($this, $fn)) {
if ($this->strict) {
throw new \Exception("Don't know how to read the format \"$format\"");
} else {
return null;
}
}
$data = $this->$fn($filename);
if (!$data) {
if ($this->strict) {
throw new \Exception("Error reading \"" . $filename . "\"");
} else {
return null;
}
}
$this->merge($data, $name, $overwrite);
}