CustomVariable: add new helper methods

toJson, checksum, render - will be used later on
This commit is contained in:
Thomas Gelf 2016-12-06 08:35:27 +01:00
parent 0bb1df2f77
commit 962e545a79
5 changed files with 77 additions and 0 deletions

View File

@ -67,6 +67,15 @@ abstract class CustomVariable implements IcingaConfigRenderer
return $this->getValue();
}
public function toJson()
{
if ($this->getDbFormat() === 'string') {
return json_encode($this->getDbValue());
} else {
return $this->getDbValue();
}
}
// TODO: abstract
public function getDbFormat()
{
@ -91,6 +100,34 @@ abstract class CustomVariable implements IcingaConfigRenderer
);
}
public function flatten(array & $flat, $prefix)
{
$flat[$prefix] = $this->getDbValue();
}
public function render($renderExpressions = false)
{
return c::renderKeyValue(
$this->renderKeyName($this->getKey()),
$this->toConfigStringPrefetchable($renderExpressions)
);
}
protected function renderKeyName($key)
{
if (preg_match('/^[a-z0-9_]+\d*$/i', $key)) {
return 'vars.' . c::escapeIfReserved($key);
} else {
return 'vars[' . c::renderString($key) . ']';
}
}
public function checksum()
{
// TODO: remember checksum, invalidate on change
return sha1($this->getKey() . '=' . $this->toJson(), true);
}
public function isNew()
{
return ! $this->loadedFromDb;

View File

@ -69,6 +69,13 @@ class CustomVariableArray extends CustomVariable
return $this;
}
public function flatten(array & $flat, $prefix)
{
foreach ($this->value as $k => $v) {
$v->flatten($flat, sprintf('%s[%d]', $prefix, $k));
}
}
public function toConfigString($renderExpressions = false)
{
$parts = array();

View File

@ -75,6 +75,13 @@ class CustomVariableDictionary extends CustomVariable implements Countable
return $ret;
}
public function flatten(array & $flat, $prefix)
{
foreach ($this->value as $k => $v) {
$v->flatten($flat, sprintf('%s["%s"]', $prefix, $k));
}
}
public function listKeys()
{
$keys = array_keys($this->value);

View File

@ -37,6 +37,12 @@ class CustomVariableString extends CustomVariable
return $this;
}
public function flatten(array & $flat, $prefix)
{
// TODO: we should get rid of type=string and always use JSON
$flat[$prefix] = json_encode($this->getValue());
}
public function toConfigString($renderExpressions = false)
{
if ($renderExpressions) {

View File

@ -273,6 +273,26 @@ class CustomVariables implements Iterator, Countable, IcingaConfigRenderer
return $this->storedVars;
}
public function flatten()
{
$flat = array();
foreach ($this->vars as $key => $var) {
$var->flatten($flat, $key);
}
return $flat;
}
public function checksum()
{
$sums = array();
foreach ($this->vars as $key => $var) {
$sums[] = $key . '=' . $var->checksum();
}
return sha1(implode('|', $sums), true);
}
public function toConfigString($renderExpressions = false)
{
$out = '';