summaryrefslogtreecommitdiffstats
path: root/library/Director/Data/PropertyMangler.php
blob: 40b257040de6005716718ec5dfcf64c577ad3bca (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
<?php

namespace Icinga\Module\Director\Data;

use Icinga\Module\Director\Objects\IcingaObject;
use InvalidArgumentException;

class PropertyMangler
{
    public static function appendToArrayProperties(IcingaObject $object, $properties)
    {
        foreach ($properties as $key => $value) {
            $current = $object->$key;
            if ($current === null) {
                $current = [$value];
            } elseif (is_array($current)) {
                $current[] = $value;
            } else {
                throw new InvalidArgumentException(sprintf(
                    'I can only append to arrays, %s is %s',
                    $key,
                    var_export($current, true)
                ));
            }

            $object->$key = $current;
        }
    }

    public static function removeProperties(IcingaObject $object, $properties)
    {
        foreach ($properties as $key => $value) {
            if ($value === true) {
                $object->$key = null;
            }
            $current = $object->$key;
            if ($current === null) {
                continue;
            } elseif (is_array($current)) {
                $new = [];
                foreach ($current as $item) {
                    if ($item !== $value) {
                        $new[] = $item;
                    }
                }
                $object->$key = $new;
            } elseif (is_string($current)) {
                if ($current === $value) {
                    $object->$key = null;
                }
            } else {
                throw new InvalidArgumentException(sprintf(
                    'I can only remove strings or from arrays, %s is %s',
                    $key,
                    var_export($current, true)
                ));
            }
        }
    }
}