From 7c58b3ced142f011db44892be03cb576e29a6949 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Thu, 19 Nov 2020 11:30:34 +0100 Subject: [PATCH] LessCompiler: Add support for variable exports by modules Using the following in a module's less file: ``` @exports: { @foo: "bar"; @number: 4; @color: red; }; ``` will export the variables `@foo`, `@number` and `@color` into the global scope. Though, exports are not able to override already defined variables. That's still reserved for themes. --- library/Icinga/Web/LessCompiler.php | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/library/Icinga/Web/LessCompiler.php b/library/Icinga/Web/LessCompiler.php index 7ebf66900..1d9aec05c 100644 --- a/library/Icinga/Web/LessCompiler.php +++ b/library/Icinga/Web/LessCompiler.php @@ -4,8 +4,6 @@ namespace Icinga\Web; use Icinga\Application\Logger; -use RecursiveArrayIterator; -use RecursiveIteratorIterator; use lessc; /** @@ -173,6 +171,7 @@ class LessCompiler } $moduleCss = ''; + $exportedVars = []; foreach ($this->moduleLessFiles as $moduleName => $moduleLessFiles) { $moduleCss .= '.icinga-module.module-' . $moduleName . ' {'; @@ -184,13 +183,36 @@ class LessCompiler } foreach ($moduleLessFiles as $moduleLessFile) { - $moduleCss .= file_get_contents($moduleLessFile); + $content = file_get_contents($moduleLessFile); + + $pattern = '/^@exports:\s*{((?:\s*@[^:}]+:[^;]*;\s+)+)};$/m'; + if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) { + foreach ($matches as $match) { + $content = str_replace($match[0], '', $content); + foreach (explode("\n", trim($match[1])) as $line) { + list($name, $value) = explode(':', $line, 2); + $exportedVars[trim($name)] = trim($value, ' ;'); + } + } + } + + $moduleCss .= $content; } + $moduleCss .= '}'; } $this->source .= $moduleCss; + $varExports = ''; + foreach ($exportedVars as $name => $value) { + $varExports .= sprintf("%s: %s;\n", $name, $value); + } + + // exported vars are injected at the beginning to avoid that they are + // able to override other variables, that's what themes are for + $this->source = $varExports . "\n\n" . $this->source; + if ($this->theme !== null) { $this->source .= file_get_contents($this->theme); }