summaryrefslogtreecommitdiffstats
path: root/library/Director/Cli/PluginOutputBeautifier.php
blob: 18a18f220da34f2e1f46ccf345d2acb0c2342a78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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]];
    }
}