summaryrefslogtreecommitdiffstats
path: root/library/X509/Model/Behavior/ExpressionInjector.php
blob: c3fa2cbee4b2df8eb93c7b40a2c3c0abcd43c92b (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
<?php

/* Icinga Web 2 X.509 Module | (c) 2022 Icinga GmbH | GPLv2 */

namespace Icinga\Module\X509\Model\Behavior;

use ipl\Orm\Contract\QueryAwareBehavior;
use ipl\Orm\Contract\RewriteFilterBehavior;
use ipl\Orm\Query;
use ipl\Sql\ExpressionInterface;
use ipl\Stdlib\Filter;

/**
 * Support expression columns (which don't really exist in the database, but rather
 * resulted e.g. from a `case..when` expression), being used as filter columns
 */
class ExpressionInjector implements RewriteFilterBehavior, QueryAwareBehavior
{
    /** @var array */
    protected $columns;

    /** @var Query */
    protected $query;

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

    public function setQuery(Query $query)
    {
        $this->query = $query;

        return $this;
    }

    public function rewriteCondition(Filter\Condition $condition, $relation = null)
    {
        $columnName = $condition->metaData()->get('columnName');
        if (in_array($columnName, $this->columns, true)) {
            $relationPath = $condition->metaData()->get('relationPath');
            if ($relationPath && $relationPath !== $this->query->getModel()->getTableAlias()) {
                $subject = $this->query->getResolver()->resolveRelation($relationPath)->getTarget();
            } else {
                $subject = $this->query->getModel();
            }

            /** @var ExpressionInterface $column */
            $column = $subject->getColumns()[$columnName];
            $expression = clone $column;
            $expression->setColumns($this->query->getResolver()->qualifyColumns(
                $this->query->getResolver()->requireAndResolveColumns(
                    $expression->getColumns(),
                    $subject
                ),
                $subject
            ));

            $condition->setColumn($this->query->getDb()->getQueryBuilder()->buildExpression($expression));
        }
    }
}