Add base for XmlConfig

2.x 2.2.0
Julien Rosset 3 years ago
parent 402b891552
commit 648165a6ad

@ -8,6 +8,20 @@ use jrosset\ArrayClasses\InsensitiveCaseArrayClass;
abstract class IniConfig extends GenericConfig implements IExternalConfigFile { abstract class IniConfig extends GenericConfig implements IExternalConfigFile {
use TMultiLevelProperties; use TMultiLevelProperties;
/**
* @inheritDoc
*/
protected function readConfig (): void {
$configFile = $this->getConfigFilePath();
if (!file_exists($configFile)) {
throw new Exception('Unable to find configuration file "' . $configFile . '"');
}
if (($iniData = parse_ini_file($configFile, true, INI_SCANNER_RAW)) === false) {
throw new Exception('Unable to read configuration file "' . $configFile . '"');
}
self::parseIniLevel($iniData, $this->properties);
}
/** /**
* Parse an INI level to properties * Parse an INI level to properties
* *
@ -26,18 +40,4 @@ abstract class IniConfig extends GenericConfig implements IExternalConfigFile {
$properties->set($iniKey, $iniValue); $properties->set($iniKey, $iniValue);
} }
} }
/**
* @inheritDoc
*/
protected function readConfig (): void {
$configFile = $this->getConfigFilePath();
if (!file_exists($configFile)) {
throw new Exception('Unable to find configuration file "' . $configFile . '"');
}
if (($iniData = parse_ini_file($configFile, true, INI_SCANNER_RAW)) === false) {
throw new Exception('Unable to read configuration file "' . $configFile . '"');
}
self::parseIniLevel($iniData, $this->properties);
}
} }

@ -0,0 +1,55 @@
<?php
namespace jrosset\EnvReader;
use Exception;
use jrosset\ArrayClasses\InsensitiveCaseArrayClass;
use SimpleXMLElement;
abstract class XmlConfig extends GenericConfig implements IExternalConfigFile {
use TMultiLevelProperties;
/**
* @inheritDoc
*/
protected function readConfig (): void {
$configFile = $this->getConfigFilePath();
if (!file_exists($configFile)) {
throw new Exception('Unable to find configuration file "' . $configFile . '"');
}
if (($xml = simplexml_load_file($configFile)) === false) {
$errors = [];
foreach (libxml_get_errors() as $error) {
$errorStr = '';
switch ($error->level) {
case LIBXML_ERR_WARNING:
$errorStr .= 'Warning';
break;
case LIBXML_ERR_ERROR:
$errorStr .= 'Error';
break;
case LIBXML_ERR_FATAL:
$errorStr .= 'Fatal error';
break;
}
$errorStr .= ' #' . $error->code . ': ' . $error->message . ' (line: ' . $error->line . ', column: ' . $error->column . ')';
$errors[] = $errorStr;
}
throw new Exception('Unable to read configuration file "' . $configFile . '": ' . PHP_EOL . implode(PHP_EOL, $errors));
}
$this->properties = $this->parseXml($xml);
}
/**
* Parse an XML node to properties
*
* @param SimpleXMLElement $xmlNode The INI level
* @param InsensitiveCaseArrayClass $properties [OUT] The out properties list
*
* @return void
*/
protected abstract function parseXml (SimpleXMLElement $xmlNode): InsensitiveCaseArrayClass;
}
Loading…
Cancel
Save