summaryrefslogtreecommitdiffstats
path: root/library/Director/Objects/IcingaObjectLegacyAssignments.php
blob: 6ab75c87958d1b66b21670240db9d66e5815c3b8 (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
<?php

namespace Icinga\Module\Director\Objects;

use LogicException;

/**
 * This class is required for historical reasons
 *
 * Objects with assignments in your activity log would otherwise not be able
 * to render themselves
 */
class IcingaObjectLegacyAssignments
{
    public static function applyToObject(IcingaObject $object, $values)
    {
        if (! $object->supportsAssignments()) {
            throw new LogicException(sprintf(
                'I can only assign for applied objects, got %s',
                $object->object_type
            ));
        }

        if ($values === null) {
            return $object;
        }

        if (! is_array($values)) {
            static::throwCompatError();
        }

        if (empty($values)) {
            return $object;
        }

        $assigns = array();
        $ignores = array();
        foreach ($values as $type => $value) {
            if (strpos($value, '|') !== false || strpos($value, '&' !== false)) {
                $value = '(' . $value . ')';
            }

            if ($type === 'assign') {
                $assigns[] = $value;
            } elseif ($type === 'ignore') {
                $ignores[] = $value;
            } else {
                static::throwCompatError();
            }
        }

        $assign = implode('|', $assigns);
        $ignore = implode('&', $ignores);
        if (empty($assign)) {
            $filter = $ignore;
        } elseif (empty($ignore)) {
            $filter = $assign;
        } else {
            if (count($assigns) === 1) {
                $filter = $assign . '&' . $ignore;
            } else {
                $filter = '(' . $assign . ')&(' . $ignore . ')';
            }
        }

        $object->assign_filter = $filter;

        return $object;
    }

    protected static function throwCompatError()
    {
        throw new LogicException(
            'You ran into an unexpected compatibility issue. Please report'
            . ' this with details helping us to reproduce this to the'
            . ' Icinga project'
        );
    }
}