summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Model/Behavior/ReRoute.php
blob: d054f00e377337eff9e2e7bbbdcf46b266b996a0 (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
<?php

/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Model\Behavior;

use ipl\Orm\Contract\RewriteFilterBehavior;
use ipl\Orm\Contract\RewritePathBehavior;
use ipl\Stdlib\Filter;

class ReRoute implements RewriteFilterBehavior, RewritePathBehavior
{
    protected $routes;

    /**
     * Tables with mixed object type entries for which servicegroup filters need to be resolved in multiple steps
     *
     * @var string[]
     */
    const MIXED_TYPE_RELATIONS = ['downtime', 'comment', 'history', 'notification_history'];

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

    public function getRoutes(): array
    {
        return $this->routes;
    }

    public function rewriteCondition(Filter\Condition $condition, $relation = null)
    {
        $remainingPath = $condition->metaData()->get('columnName', '');
        if (strpos($remainingPath, '.') === false) {
            return;
        }

        if (($path = $this->rewritePath($remainingPath, $relation)) !== null) {
            $class = get_class($condition);
            $filter = new $class($relation . $path, $condition->getValue());
            if ($condition->metaData()->has('forceOptimization')) {
                $filter->metaData()->set(
                    'forceOptimization',
                    $condition->metaData()->get('forceOptimization')
                );
            }

            if (
                in_array(substr($relation, 0, -1), self::MIXED_TYPE_RELATIONS)
                && substr($remainingPath, 0, 13) === 'servicegroup.'
            ) {
                $applyAll = Filter::all();
                $applyAll->add(Filter::equal($relation . 'object_type', 'host'));

                $orgFilter = clone $filter;
                $orgFilter->setColumn($relation . 'host.' . $path);

                $applyAll->add($orgFilter);

                $filter = Filter::any($filter, $applyAll);
            }

            return $filter;
        }
    }

    public function rewritePath(string $path, ?string $relation = null): ?string
    {
        $dot = strpos($path, '.');
        if ($dot !== false) {
            $routeName = substr($path, 0, $dot);
        } else {
            $routeName = $path;
        }

        if (isset($this->routes[$routeName])) {
            return $this->routes[$routeName] . ($dot !== false ? substr($path, $dot) : '');
        }

        return null;
    }
}