Skip to content

Commit

Permalink
Support nested keys expressed as single strings in the PreservingIniW…
Browse files Browse the repository at this point in the history
…riter

Automatically convert keys with dots into nested configurations to avoid errors during the property diff, of the old and new configuration file.
  • Loading branch information
majentsch committed Aug 26, 2014
1 parent ff1d2e4 commit 1ff63db
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions library/Icinga/Config/PreservingIniWriter.php
Expand Up @@ -38,6 +38,45 @@ public function __construct(array $options = null)
parent::__construct($options);
}

/**
* Find all keys containing dots and convert it to a nested configuration
*
* Ensure that configurations with the same ini representation the have
* similarly nested Zend_Config objects. The configuration may be altered
* during that process.
*
* @param Zend_Config $config The configuration to normalize
* @return Zend_Config The normalized config
*/
private function normalizeKeys(Zend_Config $config)
{
foreach ($config as $key => $value) {
if (preg_match('/\./', $key) > 0) {
// remove old key
unset ($config->$key);

// insert new key
$nests = explode('.', $key);
$current = $config;
$i = 0;
for (; $i < count($nests) - 1; $i++) {
if (! isset($current->{$nests[$i]})) {
// configuration key doesn't exist, create a new nesting level
$current->{$nests[$i]} = new Zend_Config (array(), true);
}
// move to next nesting level
$current = $current->{$nests[$i]};
}
// reached last nesting level, insert value
$current->{$nests[$i]} = $value;
}
if ($value instanceof Zend_Config) {
$config->$key = $this->normalizeKeys ($value);
}
}
return $config;
}

/**
* Render the Zend_Config into a config file string
*
Expand All @@ -50,6 +89,17 @@ public function render()
} else {
$oldconfig = new Zend_Config(array());
}

// create an internal copy of the given configuration, since the user of this class
// won't expect that a configuration will ever be altered during
// the rendering process.
$extends = $this->_config->getExtends();
$this->_config = new Zend_Config ($this->_config->toArray(), true);
foreach ($extends as $extending => $extended) {
$this->_config->setExtend($extending, $extended);
}
$this->_config = $this->normalizeKeys($this->_config);

$newconfig = $this->_config;
$editor = new IniEditor(file_get_contents($this->_filename), $this->options);
$this->diffConfigs($oldconfig, $newconfig, $editor);
Expand Down

0 comments on commit 1ff63db

Please sign in to comment.