summaryrefslogtreecommitdiffstats
path: root/library/Director/IcingaConfig/IcingaLegacyConfigHelper.php
blob: 38d93ee3e66d2a8d03440fcbf2046a08938dfc22 (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
<?php

namespace Icinga\Module\Director\IcingaConfig;

use InvalidArgumentException;

class IcingaLegacyConfigHelper
{
    public static function renderKeyValue($key, $value, $prefix = '    ')
    {
        return self::renderKeyOperatorValue($key, "\t", $value, $prefix);
    }

    public static function renderKeyOperatorValue($key, $operator, $value, $prefix = '    ')
    {
        $string = sprintf(
            "%s%s%s",
            $key,
            $operator,
            $value
        );

        if ($prefix && strpos($string, "\n") !== false) {
            return $prefix . implode("\n" . $prefix, explode("\n", $string)) . "\n";
        }

        return $prefix . $string . "\n";
    }

    public static function renderBoolean($value)
    {
        if ($value === 'y') {
            return '1';
        } elseif ($value === 'n') {
            return '0';
        } else {
            throw new InvalidArgumentException('%s is not a valid boolean', $value);
        }
    }

    // TODO: Double-check legacy "encoding"
    public static function renderString($string)
    {
        $special = [
            '/\\\/',
            '/\$/',
            '/\t/',
            '/\r/',
            '/\n/',
            // '/\b/', -> doesn't work
            '/\f/',
        ];

        $replace = [
            '\\\\\\',
            '\\$',
            '\\t',
            '\\r',
            '\\n',
            // '\\b',
            '\\f',
        ];

        $string = preg_replace($special, $replace, $string);

        return $string;
    }

    /**
     * @param array $array
     * @return string
     */
    public static function renderArray($array)
    {
        $data = [];
        foreach ($array as $entry) {
            if ($entry instanceof IcingaConfigRenderer) {
                // $data[] = $entry;
                $data[] = 'INVALID_ARRAY_MEMBER';
            } else {
                $data[] = self::renderString($entry);
            }
        }

        return implode(', ', $data);
    }

    public static function renderDictionary($dictionary)
    {
        return 'INVALID_DICTIONARY';
    }

    public static function renderExpression($string)
    {
        return 'INVALID_EXPRESSION';
    }

    public static function alreadyRendered($string)
    {
        return new IcingaConfigRendered($string);
    }

    public static function renderInterval($interval)
    {
        if ($interval < 60) {
            $interval = 60;
        }
        return $interval / 60;
    }
}