Add support for expressions

Any rendered string can contain variables encapsulated with "$$" characters.

Example:
Display Name declared with `Port $$host.vars.tcp_port$$ check` will
be processed as `"Port " + host.vars.tcp_port + " check"`

API:
```bash
 ./director-curl POST director/service?name=my_service '{"display_name": "Port $$host.vars.tcp_port$$ check" }'
 ```

 Rendered config:
 ```
  apply Service "my_service" {
      import "my_template"

      display_name = "Port " + host.vars.tcp_port + " check"
  }
 ```

refs #11976
This commit is contained in:
Corentin Ardeois 2016-07-29 15:58:15 -04:00 committed by Thomas Gelf
parent a9b3b2f47a
commit bcef87f4c9
2 changed files with 31 additions and 1 deletions

View File

@ -100,7 +100,7 @@ class IcingaConfigHelper
$string = preg_replace($special, $replace, $string);
return '"' . $string . '"';
return '"' . self::renderVariablesAsExpression($string) . '"';
}
public static function renderDictionaryKey($key)
@ -257,4 +257,8 @@ class IcingaConfigHelper
return $seconds . 's';
}
private static function renderVariablesAsExpression($string) {
return preg_replace('/\$\$([\w\.]+)\$\$/', '" + ${1} + "', $string);
}
}

View File

@ -69,4 +69,30 @@ class IcingaConfigHelperTest extends BaseTestCase
{
return file_get_contents(__DIR__ . '/rendered/' . $name . '.out');
}
public function testRenderStringIsCorrectlyRendered()
{
$this->assertEquals(c::renderString('val1\\\val2'), '"val1\\\\\\\\val2"');
$this->assertEquals(c::renderString('"val1"'), '"\"val1\""');
$this->assertEquals(c::renderString('\$val\$'), '"\\\\$val\\\\$"');
$this->assertEquals(c::renderString('\t'), '"\\\\t"');
$this->assertEquals(c::renderString('\r'), '"\\\\r"');
$this->assertEquals(c::renderString('\n'), '"\\\\n"');
$this->assertEquals(c::renderString('\f'), '"\\\\f"');
}
public function testRenderStringWithVariables()
{
$this->assertEquals(
c::renderString('Before $$name$$ $$name$$ After'),
'"Before " + name + " " + name + " After"');
$this->assertEquals(
c::renderString('Before $$var1$$ $$var2$$ After'),
'"Before " + var1 + " " + var2 + " After"');
$this->assertEquals(c::renderString('$$host.vars.custom$$'), '"" + host.vars.custom + ""');
$this->assertEquals(c::renderString('$$var"$$'), '"$$var\"$$"');
$this->assertEquals(
c::renderString('\tI am\rrendering\nproperly\fand I $$support$$ "multiple" $$variables$$\$'),
'"\\\\tI am\\\\rrendering\\\\nproperly\\\\fand I " + support + " \"multiple\" " + variables + "\\\\$"');
}
}