Debian Codegraph @

vendor/ipl/web/src/Compat/SearchControls.php

raw
1 <?php
2
3 namespace ipl\Web\Compat;
4
5 use GuzzleHttp\Psr7\ServerRequest;
6 use ipl\Html\Html;
7 use ipl\Orm\Exception\InvalidRelationException;
8 use ipl\Orm\Query;
9 use ipl\Stdlib\Seq;
10 use ipl\Web\Control\SearchBar;
11 use ipl\Web\Control\SearchEditor;
12 use ipl\Web\Filter\QueryString;
13 use ipl\Web\Url;
14 use ipl\Stdlib\Filter;
15
16 trait SearchControls
17 {
18 /**
19 * Fetch available filter columns for the given query
20 *
21 * @param Query $query
22 *
23 * @return array<string, string> Keys are column paths, values are labels
24 */
25 public function fetchFilterColumns(Query $query)
26 {
27 $columns = [];
28 foreach ($query->getResolver()->getColumnDefinitions($query->getModel()) as $name => $definition) {
29 $columns[$name] = $definition->getLabel();
30 }
31
32 return $columns;
33 }
34
35 /**
36 * Get whether {@see SearchControls::createSearchBar()} and {@see SearchControls::createSearchEditor()}
37 * should handle form submits.
38 *
39 * @return bool
40 */
41 private function callHandleRequest()
42 {
43 return true;
44 }
45
46 /**
47 * Create and return the SearchBar
48 *
49 * @param Query $query The query being filtered
50 * @param Url $redirectUrl Url to redirect to upon success
51 * @param array $preserveParams Query params to preserve when redirecting
52 *
53 * @return SearchBar
54 */
55 public function createSearchBar(Query $query, ...$params): SearchBar
56 {
57 $requestUrl = Url::fromRequest();
58 $preserveParams = array_pop($params) ?? [];
59 $redirectUrl = array_pop($params);
60 $paramsToAdd = $this->decodedParamValues($preserveParams, $requestUrl);
61
62 if ($redirectUrl !== null) {
63 $redirectUrl->addParams($paramsToAdd);
64 } else {
65 $redirectUrl = $requestUrl->onlyWith($preserveParams);
66 }
67
68 $filter = QueryString::fromString((string) $this->params)
69 ->on(QueryString::ON_CONDITION, function (Filter\Condition $condition) use ($query) {
70 $this->enrichFilterCondition($condition, $query);
71 })
72 ->parse();
73
74 $searchBar = new SearchBar();
75 $searchBar->setFilter($filter);
76 $searchBar->setRedirectUrl($redirectUrl);
77 $searchBar->setAction($redirectUrl->getAbsoluteUrl());
78 $searchBar->setIdProtector([$this->getRequest(), 'protectId']);
79 $searchBar->setSearchColumns($query->getModel()->getSearchColumns());
80 $searchBar->addWrapper(Html::tag('div', ['class' => 'search-controls']));
81
82 $moduleName = $this->getRequest()->getModuleName();
83 $controllerName = $this->getRequest()->getControllerName();
84
85 if (method_exists($this, 'completeAction')) {
86 $searchBar->setSuggestionUrl(Url::fromPath(
87 "$moduleName/$controllerName/complete",
88 $paramsToAdd + ['_disableLayout' => true, 'showCompact' => true]
89 ));
90 }
91
92 if (method_exists($this, 'searchEditorAction')) {
93 $searchBar->setEditorUrl(Url::fromPath(
94 "$moduleName/$controllerName/search-editor"
95 )->setParams(clone $redirectUrl->getParams()));
96 }
97
98 $filterColumns = $this->fetchFilterColumns($query);
99 $columnValidator = function (SearchBar\ValidatedColumn $column) use ($query, $filterColumns) {
100 $searchPath = $column->getSearchValue();
101 if (strpos($searchPath, '.') === false) {
102 $column->setSearchValue($query->getResolver()->qualifyPath(
103 $searchPath,
104 $query->getModel()->getTableAlias()
105 ));
106 }
107
108 try {
109 $definition = $query->getResolver()->getColumnDefinition($searchPath);
110 } catch (InvalidRelationException $_) {
111 list($columnPath, $columnLabel) = Seq::find($filterColumns, $searchPath, false);
112 if ($columnPath === null) {
113 $column->setMessage(t('Is not a valid column'));
114 $column->setSearchValue($searchPath); // Resets the qualification made above
115 } else {
116 $column->setSearchValue($columnPath);
117 $column->setLabel($columnLabel);
118 }
119 }
120
121 if (isset($definition)) {
122 if (! $definition->getName()) {
123 // Happens in case the searchPath is considered a valid relation, but without a column name
124 $column->setMessage(t('Is not a valid column'));
125 $column->setSearchValue($searchPath);
126 } else {
127 $column->setLabel($definition->getLabel());
128 }
129 }
130 };
131
132 $searchBar->on(SearchBar::ON_ADD, $columnValidator)
133 ->on(SearchBar::ON_INSERT, $columnValidator)
134 ->on(SearchBar::ON_SAVE, $columnValidator)
135 ->on(SearchBar::ON_SENT, function (SearchBar $form) {
136 /** @var Url $redirectUrl */
137 $redirectUrl = $form->getRedirectUrl();
138
139 $baseFilter = $redirectUrl->getFilter();
140 if ($baseFilter && ((! $baseFilter instanceof Filter\Chain) || ! $baseFilter->isEmpty())) {
141 $filter = Filter::all($baseFilter, $form->getFilter());
142 } else {
143 $filter = $form->getFilter();
144 }
145
146 $redirectUrl->setFilter($filter);
147 $form->setRedirectUrl($redirectUrl);
148 })->on(SearchBar::ON_SUCCESS, function (SearchBar $form) {
149 $this->getResponse()->redirectAndExit($form->getRedirectUrl());
150 });
151
152 if ($this->callHandleRequest()) {
153 $searchBar->handleRequest(ServerRequest::fromGlobals());
154 }
155
156 return $searchBar;
157 }
158
159 /**
160 * Create and return the SearchEditor
161 *
162 * @param Query $query The query being filtered
163 * @param Url $redirectUrl Url to redirect to upon success
164 * @param array $preserveParams Query params to preserve when redirecting
165 *
166 * @return SearchEditor
167 */
168 public function createSearchEditor(Query $query, ...$params): SearchEditor
169 {
170 $requestUrl = Url::fromRequest();
171 $preserveParams = array_pop($params) ?? [];
172 $redirectUrl = array_pop($params);
173 $moduleName = $this->getRequest()->getModuleName();
174 $controllerName = $this->getRequest()->getControllerName();
175 $paramsToAdd = $this->decodedParamValues($preserveParams, $requestUrl);
176
177 if ($redirectUrl !== null) {
178 $redirectUrl->addParams($paramsToAdd);
179 } else {
180 $redirectUrl = Url::fromPath("$moduleName/$controllerName")
181 ->setParams($paramsToAdd);
182 }
183
184 $editor = new SearchEditor();
185 $editor->setRedirectUrl($redirectUrl);
186 $editor->setAction($requestUrl->getAbsoluteUrl());
187 $editor->setQueryString((string) $this->params->without($preserveParams));
188
189 if (method_exists($this, 'completeAction')) {
190 $editor->setSuggestionUrl(Url::fromPath(
191 "$moduleName/$controllerName/complete",
192 $paramsToAdd + ['_disableLayout' => true, 'showCompact' => true]
193 ));
194 }
195
196 $editor->getParser()->on(QueryString::ON_CONDITION, function (Filter\Condition $condition) use ($query) {
197 if ($condition->getColumn()) {
198 $this->enrichFilterCondition($condition, $query);
199 }
200 });
201
202 $filterColumns = $this->fetchFilterColumns($query);
203 $editor->on(SearchEditor::ON_VALIDATE_COLUMN, function (
204 Filter\Condition $condition
205 ) use (
206 $query,
207 $filterColumns
208 ) {
209 $searchPath = $condition->getColumn();
210 if (strpos($searchPath, '.') === false) {
211 $condition->setColumn($query->getResolver()->qualifyPath(
212 $searchPath,
213 $query->getModel()->getTableAlias()
214 ));
215 }
216
217 try {
218 $query->getResolver()->getColumnDefinition($searchPath);
219 } catch (InvalidRelationException $_) {
220 $columnPath = Seq::findKey(
221 $filterColumns,
222 $condition->metaData()->get('columnLabel', $searchPath),
223 false
224 );
225 if ($columnPath === null) {
226 $condition->setColumn($searchPath);
227 throw new SearchBar\SearchException(t('Is not a valid column'));
228 } else {
229 $condition->setColumn($columnPath);
230 }
231 }
232 })->on(SearchEditor::ON_SUCCESS, function (SearchEditor $form) {
233 /** @var Url $redirectUrl */
234 $redirectUrl = $form->getRedirectUrl();
235
236 $baseFilter = $redirectUrl->getFilter();
237 if ($baseFilter && ((! $baseFilter instanceof Filter\Chain) || ! $baseFilter->isEmpty())) {
238 $filter = Filter::all($baseFilter, $form->getFilter());
239 } else {
240 $filter = $form->getFilter();
241 }
242
243 $redirectUrl->setFilter($filter);
244
245 $this->getResponse()
246 ->setHeader('X-Icinga-Container', '_self')
247 ->redirectAndExit($redirectUrl);
248 });
249
250 if ($this->callHandleRequest()) {
251 $editor->handleRequest(ServerRequest::fromGlobals());
252 }
253
254 return $editor;
255 }
256
257 /**
258 * Enrich the filter condition with meta data from the query
259 *
260 * @param Filter\Condition $condition
261 * @param Query $query
262 *
263 * @return void
264 */
265 protected function enrichFilterCondition(Filter\Condition $condition, Query $query)
266 {
267 $path = $condition->getColumn();
268 if (strpos($path, '.') === false) {
269 $path = $query->getResolver()->qualifyPath($path, $query->getModel()->getTableAlias());
270 $condition->setColumn($path);
271 }
272
273 try {
274 $label = $query->getResolver()->getColumnDefinition($path)->getLabel();
275 } catch (InvalidRelationException $_) {
276 $label = null;
277 }
278
279 if (isset($label)) {
280 $condition->metaData()->set('columnLabel', $label);
281 }
282 }
283
284 /**
285 * Decode the given param names from the given Url
286 *
287 * @internal This is only a helping method to prevent params being encoded multiple times in
288 * {@see SearchControls::createSearchBar()} and {@see SearchControls::createSearchEditor()}
289 * and therefore should not be used anywhere else.
290 *
291 * @return array<string, mixed> decoded key => value pairs
292 */
293 private function decodedParamValues(array $paramNames, Url $url): array
294 {
295 $params = [];
296 foreach ($paramNames as $param) {
297 $val = $url->getParam($param);
298
299 if ($val !== null) {
300 $params[$param] = $val;
301 }
302 }
303
304 return $params;
305 }
306 }