summaryrefslogtreecommitdiffstats
path: root/library/Director/CheckPlugin/PluginState.php
blob: d68ec70348286255f2af862a3407963a76280886 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php

namespace Icinga\Module\Director\CheckPlugin;

use Icinga\Exception\ProgrammingError;

class PluginState
{
    protected static $stateCodes = [
        'UNKNOWN'  => 3,
        'CRITICAL' => 2,
        'WARNING'  => 1,
        'OK'       => 0,
    ];

    protected static $stateNames = [
        'OK',
        'WARNING',
        'CRITICAL',
        'UNKNOWN',
    ];

    protected static $sortSeverity = [0, 1, 3, 2];

    /** @var int */
    protected $state;

    public function __construct($state)
    {
        $this->set($state);
    }

    public function isProblem()
    {
        return $this->state > 0;
    }

    public function set($state)
    {
        $this->state = $this->getNumericStateFor($state);
    }

    public function getNumeric()
    {
        return $this->state;
    }

    public function getSortSeverity()
    {
        return static::getSortSeverityFor($this->getNumeric());
    }

    public function getName()
    {
        return self::$stateNames[$this->getNumeric()];
    }

    public function raise(PluginState $state)
    {
        if ($this->getSortSeverity() < $state->getSortSeverity()) {
            $this->state = $state->getNumeric();
        }

        return $this;
    }

    public static function create($state)
    {
        return new static($state);
    }

    public static function ok()
    {
        return new static(0);
    }

    public static function warning()
    {
        return new static(1);
    }

    public static function critical()
    {
        return new static(2);
    }

    public static function unknown()
    {
        return new static(3);
    }

    protected static function getNumericStateFor($state)
    {
        if ((is_int($state) || ctype_digit($state)) && $state >= 0 && $state <= 3) {
            return (int) $state;
        } elseif (is_string($state) && array_key_exists($state, self::$stateCodes)) {
            return self::$stateCodes[$state];
        } else {
            throw new ProgrammingError('Expected valid state, got: %s', $state);
        }
    }

    protected static function getSortSeverityFor($state)
    {
        if (array_key_exists($state, self::$sortSeverity)) {
            return self::$sortSeverity[$state];
        } else {
            throw new ProgrammingError(
                'Unable to retrieve sort severity for invalid state: %s',
                $state
            );
        }
    }
}