From 4e083d7d40f345aee191998b4b2b82b95194e453 Mon Sep 17 00:00:00 2001 From: Thomas Gelf Date: Fri, 22 Jul 2016 18:07:56 +0200 Subject: [PATCH] CustomVariables: use array notation for keys... ...with special characters --- .../CustomVariable/CustomVariables.php | 16 ++++++-- .../CustomVariable/CustomVariablesTest.php | 41 +++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 test/php/library/Director/CustomVariable/CustomVariablesTest.php diff --git a/library/Director/CustomVariable/CustomVariables.php b/library/Director/CustomVariable/CustomVariables.php index 351819c8..a7b4c0cc 100644 --- a/library/Director/CustomVariable/CustomVariables.php +++ b/library/Director/CustomVariable/CustomVariables.php @@ -234,10 +234,18 @@ class CustomVariables implements Iterator, Countable, IcingaConfigRenderer ksort($this->vars); foreach ($this->vars as $key => $var) { - $out .= c::renderKeyValue( - 'vars.' . c::escapeIfReserved($key), - $var->toConfigString() - ); + // TODO: ctype_alnum + underscore? + if (preg_match('/^[a-z0-9_]+\d*$/i', $key)) { + $out .= c::renderKeyValue( + 'vars.' . c::escapeIfReserved($key), + $var->toConfigString() + ); + } else { + $out .= c::renderKeyValue( + 'vars[' . c::renderString($key) . ']', + $var->toConfigString() + ); + } } return $out; diff --git a/test/php/library/Director/CustomVariable/CustomVariablesTest.php b/test/php/library/Director/CustomVariable/CustomVariablesTest.php new file mode 100644 index 00000000..3c006862 --- /dev/null +++ b/test/php/library/Director/CustomVariable/CustomVariablesTest.php @@ -0,0 +1,41 @@ +newVars(); + $vars->bla = 'da'; + $vars->{'aBc'} = 'normal'; + $vars->{'a-0'} = 'special'; + $expected = $this->indentVarsList(array( + 'vars["a-0"] = "special"', + 'vars.aBc = "normal"', + 'vars.bla = "da"' + )); + $this->assertEquals( + $vars->toConfigString(), + $expected + ); + } + + protected function indentVarsList($vars) + { + return $this->indent . implode( + "\n" . $this->indent, + $vars + ) . "\n"; + } + + protected function newVars() + { + return new CustomVariables(); + } +}