summaryrefslogtreecommitdiffstats
path: root/library/Director/CustomVariable/CustomVariableNumber.php
blob: 62838a92938a5faa0e231471109eca905fa4f9c0 (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
<?php

namespace Icinga\Module\Director\CustomVariable;

use Icinga\Exception\ProgrammingError;

class CustomVariableNumber extends CustomVariable
{
    // Hint: 'F' is intentional, this MUST NOT respect locales
    const PRECISION = '%.9F';

    public function equals(CustomVariable $var)
    {
        if (! $var instanceof CustomVariableNumber) {
            return false;
        }

        $cur = $this->getValue();
        $new = $var->getValue();

        // Be tolerant when comparing floats:
        if (is_float($cur) || is_float($new)) {
            return sprintf(self::PRECISION, $cur)
                === sprintf(self::PRECISION, $new);
        }

        return $cur === $new;
    }

    public function getDbFormat()
    {
        return 'json';
    }

    public function getDbValue()
    {
        return json_encode($this->getValue());
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValue($value)
    {
        if (! is_int($value) && ! is_float($value)) {
            throw new ProgrammingError(
                'Expected a number, got %s',
                var_export($value, 1)
            );
        }

        $this->value = $value;
        $this->deleted = false;

        return $this;
    }

    public function toConfigString($renderExpressions = false)
    {
        if (is_int($this->value)) {
            return (string) $this->value;
        } else {
            return sprintf(self::PRECISION, $this->value);
        }
    }

    public function toLegacyConfigString()
    {
        return $this->toConfigString();
    }
}