1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SKien\Config; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class for config component getting data from XML file. |
8
|
|
|
* |
9
|
|
|
* @package Config |
10
|
|
|
* @author Stefanius <[email protected]> |
11
|
|
|
* @copyright MIT License - see the LICENSE file for details |
12
|
|
|
*/ |
13
|
|
|
class XMLConfig extends AbstractConfig |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The constructor expects an valid filename/path to the XML file. |
17
|
|
|
* @param string $strConfigFile |
18
|
|
|
*/ |
19
|
|
|
public function __construct(string $strConfigFile) |
20
|
|
|
{ |
21
|
|
|
$this->aConfig = $this->parseFile($strConfigFile); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Parse the given file an add all settings to the internal configuration. |
26
|
|
|
* @param string $strConfigFile |
27
|
|
|
* @return array<mixed> |
28
|
|
|
*/ |
29
|
|
|
protected function parseFile(string $strConfigFile) : array |
30
|
|
|
{ |
31
|
|
|
if (!file_exists($strConfigFile)) { |
32
|
|
|
trigger_error('Config File (' . $strConfigFile . ') does not exist!', E_USER_WARNING); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// first read XML data into stdclass object using the SimpleXML |
36
|
|
|
// to convert this object into associative array by encode it as JSON string and |
37
|
|
|
// decode it with the $assoc parameter set to true... |
38
|
|
|
$aXML = []; |
39
|
|
|
try { |
40
|
|
|
$oXML = new \SimpleXMLElement($strConfigFile, 0, true); |
41
|
|
|
$strJSON = json_encode($oXML); |
42
|
|
|
// 1. SimpleXMLElement converts an empty node to an empty SimpleXMLElement |
43
|
|
|
// 2. json_encode() converts an empty SimpleXMLElement to '{}' |
44
|
|
|
// 3. json_decode() converts '{}' to an empty array :-( |
45
|
|
|
// -> to prevent this, we replace all '{}' with an empty string '""' before decoding! |
46
|
|
|
if ($strJSON !== false) { |
47
|
|
|
$strJSON = str_replace('{}', '""', $strJSON); |
48
|
|
|
$aXML = json_decode($strJSON, true); |
49
|
|
|
} |
50
|
|
|
} catch (\Exception $e) { |
51
|
|
|
trigger_error('Invalid config file (' . $strConfigFile . '): ' . $e->getMessage(), E_USER_ERROR); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $aXML; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|