summaryrefslogtreecommitdiffstats
path: root/library/Toplevelview/Config/ConfigEmitter.php
blob: b8caff9378bf9fe4f242dd66d45f61a3a0506f1b (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
<?php
/* TopLevelView module for Icingaweb2 - Copyright (c) 2017 Icinga Development Team <info@icinga.com> */

namespace Icinga\Module\Toplevelview\Config;

use Icinga\Exception\NotImplementedError;
use stdClass;

class ConfigEmitter
{
    /** @var array */
    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    public static function classToArray($obj)
    {
        $arr = array();
        foreach (get_object_vars($obj) as $k => $v) {
            if ($k !== 'children') {
                $arr[$k] = $v;
            }
        }

        // handle children last for visibility
        if (property_exists($obj, 'children')) {
            $arr['children'] = array();
            foreach ($obj->children as $child) {
                // convert each child to an array
                $arr['children'][] = static::classToArray($child);
            }
        }

        return $arr;
    }

    public static function fromLegacyTree(stdClass $tree)
    {
        return new static(static::classToArray($tree));
    }

    public function emitJSON(&$contentType = null)
    {
        $contentType = 'application/json';
        return json_encode($this->config);
    }

    public function emitYAML(&$contentType = null)
    {
        $contentType = 'application/yaml';
        return yaml_emit($this->config, YAML_UTF8_ENCODING, YAML_LN_BREAK);
    }

    public function emitEXPORT(&$contentType = null)
    {
        $contentType = 'text/plain';
        return var_export($this->config, true);
    }

    public function emit($format, &$contentType = null)
    {
        $funcName = 'emit' . strtoupper($format);
        if (method_exists($this, $funcName)) {
            return $this->$funcName($contentType);
        } else {
            throw new NotImplementedError('format "%s" is not implemented to emit!', $format);
        }
    }
}