summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/web/src/Compat/SearchControls.php
blob: f6e74aba72231a0756d023599e78f43de64102ea (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php

namespace ipl\Web\Compat;

use GuzzleHttp\Psr7\ServerRequest;
use ipl\Html\Html;
use ipl\Orm\Exception\InvalidRelationException;
use ipl\Orm\Query;
use ipl\Stdlib\Seq;
use ipl\Web\Control\SearchBar;
use ipl\Web\Control\SearchEditor;
use ipl\Web\Filter\QueryString;
use ipl\Web\Url;
use ipl\Stdlib\Filter;

trait SearchControls
{
    /**
     * Fetch available filter columns for the given query
     *
     * @param Query $query
     *
     * @return array<string, string> Keys are column paths, values are labels
     */
    public function fetchFilterColumns(Query $query)
    {
        $columns = [];
        foreach ($query->getResolver()->getColumnDefinitions($query->getModel()) as $name => $definition) {
            $columns[$name] = $definition->getLabel();
        }

        return $columns;
    }

    /**
     * Get whether {@see SearchControls::createSearchBar()} and {@see SearchControls::createSearchEditor()}
     * should handle form submits.
     *
     * @return bool
     */
    private function callHandleRequest()
    {
        return true;
    }

    /**
     * Create and return the SearchBar
     *
     * @param Query $query The query being filtered
     * @param Url $redirectUrl Url to redirect to upon success
     * @param array $preserveParams Query params to preserve when redirecting
     *
     * @return SearchBar
     */
    public function createSearchBar(Query $query, ...$params): SearchBar
    {
        $requestUrl = Url::fromRequest();
        $preserveParams = array_pop($params) ?? [];
        $redirectUrl = array_pop($params);

        if ($redirectUrl !== null) {
            $redirectUrl->addParams($requestUrl->onlyWith($preserveParams)->getParams()->toArray(false));
        } else {
            $redirectUrl = $requestUrl->onlyWith($preserveParams);
        }

        $filter = QueryString::fromString((string) $this->params)
            ->on(QueryString::ON_CONDITION, function (Filter\Condition $condition) use ($query) {
                $this->enrichFilterCondition($condition, $query);
            })
            ->parse();

        $searchBar = new SearchBar();
        $searchBar->setFilter($filter);
        $searchBar->setRedirectUrl($redirectUrl);
        $searchBar->setAction($redirectUrl->getAbsoluteUrl());
        $searchBar->setIdProtector([$this->getRequest(), 'protectId']);
        $searchBar->addWrapper(Html::tag('div', ['class' => 'search-controls']));

        $moduleName = $this->getRequest()->getModuleName();
        $controllerName = $this->getRequest()->getControllerName();

        if (method_exists($this, 'completeAction')) {
            $searchBar->setSuggestionUrl(Url::fromPath(
                "$moduleName/$controllerName/complete",
                ['_disableLayout' => true, 'showCompact' => true]
            ));
        }

        if (method_exists($this, 'searchEditorAction')) {
            $searchBar->setEditorUrl(Url::fromPath(
                "$moduleName/$controllerName/search-editor"
            )->setParams($redirectUrl->getParams()));
        }

        $filterColumns = $this->fetchFilterColumns($query);
        $columnValidator = function (SearchBar\ValidatedColumn $column) use ($query, $filterColumns) {
            $searchPath = $column->getSearchValue();
            if (strpos($searchPath, '.') === false) {
                $column->setSearchValue($query->getResolver()->qualifyPath(
                    $searchPath,
                    $query->getModel()->getTableAlias()
                ));
            }

            try {
                $definition = $query->getResolver()->getColumnDefinition($searchPath);
            } catch (InvalidRelationException $_) {
                list($columnPath, $columnLabel) = Seq::find($filterColumns, $searchPath, false);
                if ($columnPath === null) {
                    $column->setMessage(t('Is not a valid column'));
                    $column->setSearchValue($searchPath); // Resets the qualification made above
                } else {
                    $column->setSearchValue($columnPath);
                    $column->setLabel($columnLabel);
                }
            }

            if (isset($definition)) {
                $column->setLabel($definition->getLabel());
            }
        };

        $searchBar->on(SearchBar::ON_ADD, $columnValidator)
            ->on(SearchBar::ON_INSERT, $columnValidator)
            ->on(SearchBar::ON_SAVE, $columnValidator)
            ->on(SearchBar::ON_SENT, function (SearchBar $form) {
                /** @var Url $redirectUrl */
                $redirectUrl = $form->getRedirectUrl();
                $redirectUrl->setFilter($form->getFilter());
                $form->setRedirectUrl($redirectUrl);
            })->on(SearchBar::ON_SUCCESS, function (SearchBar $form) {
                $this->getResponse()->redirectAndExit($form->getRedirectUrl());
            });

        if ($this->callHandleRequest()) {
            $searchBar->handleRequest(ServerRequest::fromGlobals());
        }

        return $searchBar;
    }

    /**
     * Create and return the SearchEditor
     *
     * @param Query $query The query being filtered
     * @param Url $redirectUrl Url to redirect to upon success
     * @param array $preserveParams Query params to preserve when redirecting
     *
     * @return SearchEditor
     */
    public function createSearchEditor(Query $query, ...$params): SearchEditor
    {
        $requestUrl = Url::fromRequest();
        $preserveParams = array_pop($params) ?? [];
        $redirectUrl = array_pop($params);
        $moduleName = $this->getRequest()->getModuleName();
        $controllerName = $this->getRequest()->getControllerName();

        if ($redirectUrl !== null) {
            $redirectUrl->addParams($requestUrl->onlyWith($preserveParams)->getParams()->toArray(false));
        } else {
            $redirectUrl = Url::fromPath("$moduleName/$controllerName");
            if (! empty($preserveParams)) {
                $redirectUrl->setParams($requestUrl->onlyWith($preserveParams)->getParams());
            }
        }

        $editor = new SearchEditor();
        $editor->setRedirectUrl($redirectUrl);
        $editor->setAction($requestUrl->getAbsoluteUrl());
        $editor->setQueryString((string) $this->params->without($preserveParams));

        if (method_exists($this, 'completeAction')) {
            $editor->setSuggestionUrl(Url::fromPath(
                "$moduleName/$controllerName/complete",
                ['_disableLayout' => true, 'showCompact' => true]
            ));
        }

        $editor->getParser()->on(QueryString::ON_CONDITION, function (Filter\Condition $condition) use ($query) {
            if ($condition->getColumn()) {
                $this->enrichFilterCondition($condition, $query);
            }
        });

        $filterColumns = $this->fetchFilterColumns($query);
        $editor->on(SearchEditor::ON_VALIDATE_COLUMN, function (
            Filter\Condition $condition
        ) use (
            $query,
            $filterColumns
        ) {
            $searchPath = $condition->getColumn();
            if (strpos($searchPath, '.') === false) {
                $condition->setColumn($query->getResolver()->qualifyPath(
                    $searchPath,
                    $query->getModel()->getTableAlias()
                ));
            }

            try {
                $query->getResolver()->getColumnDefinition($searchPath);
            } catch (InvalidRelationException $_) {
                $columnPath = Seq::findKey(
                    $filterColumns,
                    $condition->metaData()->get('columnLabel', $searchPath),
                    false
                );
                if ($columnPath === null) {
                    $condition->setColumn($searchPath);
                    throw new SearchBar\SearchException(t('Is not a valid column'));
                } else {
                    $condition->setColumn($columnPath);
                }
            }
        })->on(SearchEditor::ON_SUCCESS, function (SearchEditor $form) {
            /** @var Url $redirectUrl */
            $redirectUrl = $form->getRedirectUrl();
            $redirectUrl->setFilter($form->getFilter());

            $this->getResponse()
                ->setHeader('X-Icinga-Container', '_self')
                ->redirectAndExit($redirectUrl);
        });

        if ($this->callHandleRequest()) {
            $editor->handleRequest(ServerRequest::fromGlobals());
        }

        return $editor;
    }

    /**
     * Enrich the filter condition with meta data from the query
     *
     * @param Filter\Condition $condition
     * @param Query $query
     *
     * @return void
     */
    protected function enrichFilterCondition(Filter\Condition $condition, Query $query)
    {
        $path = $condition->getColumn();
        if (strpos($path, '.') === false) {
            $path = $query->getResolver()->qualifyPath($path, $query->getModel()->getTableAlias());
            $condition->setColumn($path);
        }

        try {
            $label = $query->getResolver()->getColumnDefinition($path)->getLabel();
        } catch (InvalidRelationException $_) {
            $label = null;
        }

        if (isset($label)) {
            $condition->metaData()->set('columnLabel', $label);
        }
    }
}