diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-14 13:17:31 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-14 13:17:31 +0000 |
commit | f66ab8dae2f3d0418759f81a3a64dc9517a62449 (patch) | |
tree | fbff2135e7013f196b891bbde54618eb050e4aaf /library/Director/Cli/PluginOutputBeautifier.php | |
parent | Initial commit. (diff) | |
download | icingaweb2-module-director-f66ab8dae2f3d0418759f81a3a64dc9517a62449.tar.xz icingaweb2-module-director-f66ab8dae2f3d0418759f81a3a64dc9517a62449.zip |
Adding upstream version 1.10.2.upstream/1.10.2
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r-- | library/Director/Cli/PluginOutputBeautifier.php | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/library/Director/Cli/PluginOutputBeautifier.php b/library/Director/Cli/PluginOutputBeautifier.php new file mode 100644 index 0000000..18a18f2 --- /dev/null +++ b/library/Director/Cli/PluginOutputBeautifier.php @@ -0,0 +1,75 @@ +<?php + +namespace Icinga\Module\Director\Cli; + +use Icinga\Cli\Screen; + +class PluginOutputBeautifier +{ + /** @var Screen */ + protected $screen; + + protected $isTty; + + protected $colorized; + + public function __construct(Screen $screen) + { + $this->screen = $screen; + } + + public static function beautify($string, Screen $screen) + { + $self = new static($screen); + if ($self->isTty()) { + return $self->colorizeStates($string); + } else { + return $string; + } + } + + protected function colorizeStates($string) + { + $string = preg_replace_callback( + "/'([^']+)'/", + [$this, 'highlightNames'], + $string + ); + + $string = preg_replace_callback( + '/(OK|WARNING|CRITICAL|UNKNOWN)/', + [$this, 'getColorized'], + $string + ); + + return $string; + } + + protected function isTty() + { + if ($this->isTty === null) { + $this->isTty = function_exists('posix_isatty') && posix_isatty(STDOUT); + } + + return $this->isTty; + } + + protected function highlightNames($match) + { + return "'" . $this->screen->colorize($match[1], 'darkgray') . "'"; + } + + protected function getColorized($match) + { + if ($this->colorized === null) { + $this->colorized = [ + 'OK' => $this->screen->colorize('OK', 'lightgreen'), + 'WARNING' => $this->screen->colorize('WARNING', 'yellow'), + 'CRITICAL' => $this->screen->colorize('CRITICAL', 'lightred'), + 'UNKNOWN' => $this->screen->colorize('UNKNOWN', 'lightpurple'), + ]; + } + + return $this->colorized[$match[1]]; + } +} |