From f1bd2e73892203f48fa7eff7c84555e6b5e0f43a Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 10 Dec 2019 10:54:46 +0100 Subject: [PATCH] Introduce class `CustomvarFilter` --- library/Icingadb/Compat/CustomvarFilter.php | 98 +++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 library/Icingadb/Compat/CustomvarFilter.php diff --git a/library/Icingadb/Compat/CustomvarFilter.php b/library/Icingadb/Compat/CustomvarFilter.php new file mode 100644 index 00000000..614507f6 --- /dev/null +++ b/library/Icingadb/Compat/CustomvarFilter.php @@ -0,0 +1,98 @@ +objectType = $objectType; + + if (! empty($restrictions)) { + $this->filter = new GlobFilter($restrictions); + } + + if ($toObfuscate) { + $patterns = []; + foreach (explode(',', $toObfuscate) as $pattern) { + $nonWildcards = []; + foreach (explode('*', $pattern) as $nonWildcard) { + $nonWildcards[] = preg_quote($nonWildcard, '/'); + } + + $patterns[] = implode('.*', $nonWildcards); + } + + $this->toObfuscate = '/^(' . join('|', $patterns) . ')$/i'; + } + + parent::__construct($iterator); + } + + public function accept() + { + if ($this->filter === null) { + return true; + } + + $model = $this->getInnerIterator()->current(); + + $this->currentResult = $this->filter->removeMatching([ + $this->objectType => [ + 'vars' => [ + $model->name => $model->value + ] + ] + ]); + + return isset($this->currentResult[$this->objectType]['vars'][$model->name]); + } + + public function current() + { + $model = parent::current(); + + if ($this->filter !== null) { + $model->value = $this->currentResult[$this->objectType]['vars'][$model->name]; + } + + if ($this->toObfuscate !== null) { + $model->value = $this->obfuscate($model->name, $model->value); + } + + return $model; + } + + protected function obfuscate($name, $value) + { + if (preg_match($this->toObfuscate, $name)) { + return '***'; + } elseif (is_scalar($value)) { + return $value; + } + + $obfuscatedVars = []; + foreach (arrayval($value) as $nestedName => $nestedValue) { + $obfuscatedVars[$nestedName] = $this->obfuscate($nestedName, $nestedValue); + } + + return $value instanceof stdClass ? (object) $obfuscatedVars : $obfuscatedVars; + } +}