-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathConfigurationPhpUnitVars.php
103 lines (93 loc) · 2.56 KB
/
ConfigurationPhpUnitVars.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* Configuration to get the config from xml files
*
* @author Fabrizio Branca
*/
class Menta_ConfigurationPhpUnitVars implements Menta_Interface_Configuration {
/**
* @var Menta_ConfigurationPhpUnitVars
*/
protected static $instance;
/**
* @var array
*/
protected static $configurationFiles = array();
/**
* @static
* @throws InvalidArgumentException
* @param $configurationFile
* @return void
*/
public static function addConfigurationFile($configurationFile) {
if (!is_file($configurationFile)) {
throw new InvalidArgumentException("Could not find file '$configurationFile'");
}
self::$configurationFiles[] = $configurationFile;
}
/**
* Get singleton instance
*
* @return Menta_ConfigurationPhpUnitVars
*/
public static function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new Menta_ConfigurationPhpUnitVars();
}
return self::$instance;
}
/**
* Get configuration value
*
* @throws Exception if key is not found
* @param string $key
* @return string
*/
public function getValue($key) {
if (empty($GLOBALS[__CLASS__.'_defaultsLoaded'])) {
$this->loadDefaults();
}
if (!$this->issetKey($key)) {
throw new Exception(sprintf('Could not find configuration key "%s"', $key));
}
// json decoding if possible
$jsonDecoded = json_decode($GLOBALS[$key], true);
if (!is_null($jsonDecoded)) {
$GLOBALS[$key] = $jsonDecoded;
}
return $GLOBALS[$key];
}
/**
* Check if key is set
*
* @param string $key
* @return boolean
*/
public function issetKey($key) {
if (empty($GLOBALS[__CLASS__.'_defaultsLoaded'])) {
$this->loadDefaults();
}
return isset($GLOBALS[$key]);
}
/**
* Read values from file and stores them into $GLOBALS without overriding existing values
*
* @return void
*/
protected function loadDefaults() {
foreach (self::$configurationFiles as $xmlfile) {
if (file_exists($xmlfile)) {
$xml = simplexml_load_file($xmlfile);
foreach ($xml->xpath('//phpunit/php/var') as $node) { /* @var $node SimpleXMLElement */
$key = (string)$node['name'];
if (!isset($GLOBALS[$key])) { // only set the default value if no other value is set
$GLOBALS[$key] = (string)$node['value'];
}
}
}
}
// storing information to globals instead of static properties. So if globals will
// be restored this information also gets lost and will trigger reloading of the defaults
$GLOBALS[__CLASS__.'_defaultsLoaded'] = true;
}
}