summaryrefslogtreecommitdiffstats
path: root/library/Director/CheckPlugin/Range.php
blob: d7b582ea99f424043956c6337fb037c7a4bba103 (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
<?php

namespace Icinga\Module\Director\CheckPlugin;

use Icinga\Exception\ConfigurationError;

class Range
{
    /** @var float|null */
    protected $start = 0;

    /** @var float|null */
    protected $end = null;

    /** @var bool */
    protected $mustBeWithinRange = true;

    public function __construct($start = 0, $end = null, $mustBeWithinRange = true)
    {
        $this->start = $start;
        $this->end = $end;
        $this->mustBeWithinRange = $mustBeWithinRange;
    }

    public function valueIsValid($value)
    {
        if ($this->valueIsWithinRange($value)) {
            return $this->valueMustBeWithinRange();
        } else {
            return ! $this->valueMustBeWithinRange();
        }
    }

    public function valueIsWithinRange($value)
    {
        if ($this->start !== null && $value < $this->start) {
            return false;
        }
        if ($this->end !== null && $value > $this->end) {
            return false;
        }

        return true;
    }

    public function valueMustBeWithinRange()
    {
        return $this->mustBeWithinRange;
    }

    /**
     * @param $any
     * @return static
     */
    public static function wantRange($any)
    {
        if ($any instanceof static) {
            return $any;
        } else {
            return static::parse($any);
        }
    }

    /**
     * @param $string
     * @return static
     * @throws ConfigurationError
     */
    public static function parse($string)
    {
        $string = str_replace(' ', '', $string);
        $value = '[-+]?[\d\.]+';
        $valueRe = "$value(?:e$value)?";
        $regex = "/^(@)?($valueRe|~)(:$valueRe|~)?/";
        if (! preg_match($regex, $string, $match)) {
            throw new ConfigurationError('Invalid range definition: %s', $string);
        }

        $inside = $match[1] === '@';

        if (strlen($match[3]) === 0) {
            $start = 0;
            $end = static::parseValue($match[2]);
        } else {
            $start = static::parseValue($match[2]);
            $end = static::parseValue($match[3]);
        }
        $range = new static($start, $end, $inside);

        return $range;
    }

    protected static function parseValue($value)
    {
        if ($value === '~') {
            return null;
        } else {
            return $value;
        }
    }
}