Debian Codegraph @

vendor/ipl/web/src/Control/SearchBar.php

raw
1 <?php
2
3 namespace ipl\Web\Control;
4
5 use ipl\Html\Attributes;
6 use ipl\Html\Form;
7 use ipl\Html\FormElement\HiddenElement;
8 use ipl\Html\FormElement\InputElement;
9 use ipl\Html\FormElement\SubmitElement;
10 use ipl\Html\HtmlDocument;
11 use ipl\Html\HtmlElement;
12 use ipl\Stdlib\Filter;
13 use ipl\Validator\CallbackValidator;
14 use ipl\Web\Common\FormUid;
15 use ipl\Web\Control\SearchBar\Terms;
16 use ipl\Web\Control\SearchBar\ValidatedColumn;
17 use ipl\Web\Control\SearchBar\ValidatedOperator;
18 use ipl\Web\Control\SearchBar\ValidatedTerm;
19 use ipl\Web\Control\SearchBar\ValidatedValue;
20 use ipl\Web\Filter\ParseException;
21 use ipl\Web\Filter\Parser;
22 use ipl\Web\Filter\QueryString;
23 use ipl\Web\Url;
24 use ipl\Web\Widget\Icon;
25
26 class SearchBar extends Form
27 {
28 use FormUid;
29
30 /** @var string Emitted in case the user added a new condition */
31 public const ON_ADD = 'on_add';
32
33 /** @var string Emitted in case the user inserted a new condition */
34 public const ON_INSERT = 'on_insert';
35
36 /** @var string Emitted in case the user changed an existing condition */
37 public const ON_SAVE = 'on_save';
38
39 /** @var string Emitted in case the user removed a condition */
40 public const ON_REMOVE = 'on_remove';
41
42 protected $defaultAttributes = [
43 'data-enrichment-type' => 'search-bar',
44 'class' => 'search-bar',
45 'name' => 'search-bar',
46 'role' => 'search'
47 ];
48
49 /** @var Url */
50 protected $editorUrl;
51
52 /** @var Filter\Rule */
53 protected $filter;
54
55 /** @var string */
56 protected $searchParameter;
57
58 /** @var string[] */
59 protected array $searchColumns = [];
60
61 /** @var Url */
62 protected $suggestionUrl;
63
64 /** @var string */
65 protected $submitLabel;
66
67 /** @var callable */
68 protected $protector;
69
70 /** @var array */
71 protected $changes;
72
73 /**
74 * Set the url from which to load the editor
75 *
76 * @param Url $url
77 *
78 * @return $this
79 */
80 public function setEditorUrl(Url $url)
81 {
82 $this->editorUrl = $url;
83
84 return $this;
85 }
86
87 /**
88 * Get the url from which to load the editor
89 *
90 * @return Url
91 */
92 public function getEditorUrl()
93 {
94 return $this->editorUrl;
95 }
96
97 /**
98 * Set the filter to use
99 *
100 * @param Filter\Rule $filter
101 * @return $this
102 */
103 public function setFilter(Filter\Rule $filter)
104 {
105 $this->filter = $filter;
106
107 return $this;
108 }
109
110 /**
111 * Get the filter in use
112 *
113 * @return Filter\Rule
114 */
115 public function getFilter()
116 {
117 return $this->filter;
118 }
119
120 /**
121 * Set the search parameter to use
122 *
123 * @param string $name
124 * @return $this
125 */
126 public function setSearchParameter($name)
127 {
128 $this->searchParameter = $name;
129
130 return $this;
131 }
132
133 /**
134 * Get the search parameter in use
135 *
136 * @return string
137 */
138 public function getSearchParameter()
139 {
140 return $this->searchParameter ?: 'q';
141 }
142
143 /**
144 * Set the search columns to use
145 *
146 * @param string[] $columns
147 *
148 * @return $this
149 */
150 public function setSearchColumns(array $columns): static
151 {
152 $this->searchColumns = $columns;
153
154 return $this;
155 }
156
157 /**
158 * Get the search columns in use
159 *
160 * @return string[]
161 */
162 public function getSearchColumns(): array
163 {
164 return $this->searchColumns;
165 }
166
167 /**
168 * Set the suggestion url
169 *
170 * @param Url $url
171 * @return $this
172 */
173 public function setSuggestionUrl(Url $url)
174 {
175 $this->suggestionUrl = $url;
176
177 return $this;
178 }
179
180 /**
181 * Get the suggestion url
182 *
183 * @return Url
184 */
185 public function getSuggestionUrl()
186 {
187 return $this->suggestionUrl;
188 }
189
190 /**
191 * Set the submit label
192 *
193 * @param string $label
194 * @return $this
195 */
196 public function setSubmitLabel($label)
197 {
198 $this->submitLabel = $label;
199
200 return $this;
201 }
202
203 /**
204 * Get the submit label
205 *
206 * @return string
207 */
208 public function getSubmitLabel()
209 {
210 return $this->submitLabel;
211 }
212
213 /**
214 * Set callback to protect ids with
215 *
216 * @param callable $protector
217 *
218 * @return $this
219 */
220 public function setIdProtector($protector)
221 {
222 $this->protector = $protector;
223
224 return $this;
225 }
226
227 /**
228 * Get changes to be applied on the client
229 *
230 * @return array
231 */
232 public function getChanges()
233 {
234 return $this->changes;
235 }
236
237 private function protectId($id)
238 {
239 if (is_callable($this->protector)) {
240 return call_user_func($this->protector, $id);
241 }
242
243 return $id;
244 }
245
246 public function populate($values)
247 {
248 if (array_key_exists($this->getSearchParameter(), (array) $values)) {
249 // If a filter is set, it must be reset in case new data arrives. The new data controls the filter,
250 // though if no data is sent, (populate() is only called if the form is sent) then the filter must
251 // be reset explicitly here to not keep the outdated filter.
252 $this->filter = Filter::all();
253 }
254
255 parent::populate($values);
256 }
257
258 public function isValidEvent($event)
259 {
260 switch ($event) {
261 case self::ON_ADD:
262 case self::ON_SAVE:
263 case self::ON_INSERT:
264 case self::ON_REMOVE:
265 return true;
266 default:
267 return parent::isValidEvent($event);
268 }
269 }
270
271 private function validateCondition($eventType, $indices, $termsData, &$changes)
272 {
273 // TODO: In case of the query string validation, all three are guaranteed to be set.
274 // The Parser also provides defaults, why shouldn't we here?
275 $column = ValidatedColumn::fromTermData($termsData[0]);
276 $operator = isset($termsData[1])
277 ? ValidatedOperator::fromTermData($termsData[1])
278 : null;
279 $value = isset($termsData[2])
280 ? ValidatedValue::fromTermData($termsData[2])
281 : null;
282
283 $this->emit($eventType, [$column, $operator, $value]);
284
285 if ($eventType !== self::ON_REMOVE) {
286 if (! $column->isValid() || $column->hasBeenChanged()) {
287 $changes[$indices[0]] = array_merge($termsData[0], $column->toTermData());
288 }
289
290 if ($operator && ! $operator->isValid()) {
291 $changes[$indices[1]] = array_merge($termsData[1], $operator->toTermData());
292 }
293
294 if ($value && (! $value->isValid() || $value->hasBeenChanged())) {
295 $changes[$indices[2]] = array_merge($termsData[2], $value->toTermData());
296 }
297 }
298
299 return $column->isValid() && (! $operator || $operator->isValid()) && (! $value || $value->isValid());
300 }
301
302
303 protected function assemble()
304 {
305 $termContainerId = $this->protectId('terms');
306 $termInputId = $this->protectId('term-input');
307 $dataInputId = $this->protectId('data-input');
308 $searchInputId = $this->protectId('search-input');
309 $suggestionsId = $this->protectId('suggestions');
310
311 $termContainer = (new Terms())->setAttribute('id', $termContainerId);
312 $termInput = new HiddenElement($this->getSearchParameter(), [
313 'id' => $termInputId,
314 'disabled' => true
315 ]);
316
317 if (! $this->getRequest()->getHeaderLine('X-Icinga-Autorefresh')) {
318 $termContainer->setFilter(function () {
319 return $this->getFilter();
320 });
321 $termInput->getAttributes()->registerAttributeCallback('value', function () {
322 return QueryString::render($this->getFilter());
323 });
324 }
325
326 $dataInput = new HiddenElement('data', [
327 'id' => $dataInputId,
328 'validators' => [
329 new CallbackValidator(function ($data, CallbackValidator $_) use ($termContainer, $searchInputId) {
330 $data = $data ? json_decode($data, true) : null;
331 if (empty($data)) {
332 return true;
333 }
334
335 switch ($data['type']) {
336 case 'add':
337 case 'exchange':
338 $type = self::ON_ADD;
339
340 break;
341 case 'insert':
342 $type = self::ON_INSERT;
343
344 break;
345 case 'save':
346 $type = self::ON_SAVE;
347
348 break;
349 case 'remove':
350 $type = self::ON_REMOVE;
351
352 break;
353 default:
354 return true;
355 }
356
357 $changes = [];
358 $invalid = false;
359 $indices = [null, null, null];
360 $termsData = [null, null, null];
361 foreach (isset($data['terms']) ? $data['terms'] : [] as $termIndex => $termData) {
362 switch ($termData['type']) {
363 case 'column':
364 $indices[0] = $termIndex;
365 $termsData[0] = $termData;
366
367 break;
368 case 'operator':
369 $indices[1] = $termIndex;
370 $termsData[1] = $termData;
371
372 break;
373 case 'value':
374 $indices[2] = $termIndex;
375 $termsData[2] = $termData;
376
377 break;
378 default:
379 if ($termsData[0] !== null) {
380 if (! $this->validateCondition($type, $indices, $termsData, $changes)) {
381 $invalid = true;
382 }
383 }
384
385 $indices = $termsData = [null, null, null];
386 }
387 }
388
389 if ($termsData[0] !== null) {
390 if (! $this->validateCondition($type, $indices, $termsData, $changes)) {
391 $invalid = true;
392 }
393 }
394
395 if (! empty($changes)) {
396 $this->changes = ['#' . $searchInputId, $changes];
397 $termContainer->applyChanges($changes);
398 }
399
400 return ! $invalid;
401 })
402 ]
403 ]);
404 $this->registerElement($dataInput);
405
406 $filterInput = new InputElement($this->getSearchParameter(), [
407 'type' => 'text',
408 'placeholder' => 'Type to search. Use * as wildcard.',
409 'class' => 'filter-input',
410 'id' => $searchInputId,
411 'autocomplete' => 'off',
412 'data-enrichment-type' => 'filter',
413 'data-data-input' => '#' . $dataInputId,
414 'data-term-input' => '#' . $termInputId,
415 'data-term-container' => '#' . $termContainerId,
416 'data-term-suggestions' => '#' . $suggestionsId,
417 'data-missing-log-op' => t('Please add a logical operator on the left.'),
418 'data-incomplete-group' => t('Please close or remove this group.'),
419 'data-choose-template' => t('Please type one of: %s', '..<comma separated list>'),
420 'data-choose-column' => t('Please enter a valid column.'),
421 'validators' => [
422 new CallbackValidator(function ($q, CallbackValidator $validator) use ($searchInputId) {
423 $submitted = $this->hasBeenSubmitted();
424 $invalid = false;
425 $changes = [];
426
427 $parser = QueryString::fromString($q);
428 $parser->on(QueryString::ON_CONDITION, function (Filter\Condition $condition) use (
429 &$invalid,
430 &$changes,
431 $submitted
432 ) {
433 $columnIndex = $condition->metaData()->get('columnIndex');
434 if (isset($this->changes[1][$columnIndex])) {
435 $change = $this->changes[1][$columnIndex];
436 $condition->setColumn($change['search']);
437 } else {
438 $column = ValidatedColumn::fromFilterCondition($condition);
439 $operator = ValidatedOperator::fromFilterCondition($condition);
440 $value = ValidatedValue::fromFilterCondition($condition);
441 $this->emit(self::ON_ADD, [$column, $operator, $value]);
442
443 $condition->setColumn($column->getSearchValue());
444 $condition->setValue($value->getSearchValue());
445
446 if (! $column->isValid()) {
447 $invalid = true;
448
449 if ($submitted) {
450 $condition->metaData()->merge($column->toMetaData());
451 } else {
452 $changes[$columnIndex] = $column->toTermData();
453 }
454 }
455
456 if (! $operator->isValid()) {
457 $invalid = true;
458
459 if ($submitted) {
460 $condition->metaData()->merge($operator->toMetaData());
461 } else {
462 $changes[$condition->metaData()->get('operatorIndex')] = $operator->toTermData();
463 }
464 }
465
466 if (! $value->isValid()) {
467 $invalid = true;
468
469 if ($submitted) {
470 $condition->metaData()->merge($value->toMetaData());
471 } else {
472 $changes[$condition->metaData()->get('valueIndex')] = $value->toTermData();
473 }
474 }
475 }
476 });
477
478 try {
479 $filter = $parser->parse();
480 } catch (ParseException $e) {
481 $charAt = $e->getCharPos();
482 $char = $e->getChar();
483
484 if ($char === Parser::EOL) {
485 $value = $q;
486 $title = t('Unexpected end of input');
487 $pattern = sprintf(
488 ValidatedTerm::DEFAULT_PATTERN,
489 ValidatedTerm::escapeForHTMLPattern($q)
490 );
491 } else {
492 $value = substr($q, $charAt);
493 $title = sprintf(t('Unexpected %s at start of input'), $char);
494 $pattern = sprintf('^(?!%s).*', ValidatedTerm::escapeForHTMLPattern($char));
495
496 if ($charAt > 0) {
497 try {
498 $this->setFilter(QueryString::parse(substr($q, 0, $charAt)));
499 } catch (ParseException) {
500 $value = $q;
501 $title = sprintf(t('Unexpected %s at position %d'), $char, $charAt + 1);
502 $pattern = sprintf(
503 ValidatedTerm::DEFAULT_PATTERN,
504 ValidatedTerm::escapeForHTMLPattern($q)
505 );
506 }
507 }
508 }
509
510 $this->getElement($this->getSearchParameter())
511 ->addAttributes([
512 'title' => $title,
513 'pattern' => $pattern,
514 'data-has-syntax-error' => true
515 ])
516 ->getAttributes()
517 ->registerAttributeCallback('value', function () use ($value) {
518 return $value;
519 });
520
521 return false;
522 }
523
524 if (
525 $this->getSearchColumns()
526 && $filter instanceof Filter\Condition
527 // The parser yields a boolean but the validation may cast this to a string -.-
528 && ($filter->getValue() === '1' || $filter->getValue() === true)
529 && $filter->metaData()->has('invalidColumnMessage')
530 ) {
531 // A single expression that's invalid and has only a truthy value can be safely
532 // be transformed to a quick search
533 $changes = [];
534 $change = 0;
535 $filter = Filter::any();
536 foreach ($this->getSearchColumns() as $column) {
537 $condition = Filter::like($column, "*$q*");
538 $column = ValidatedColumn::fromFilterCondition($condition);
539 $operator = ValidatedOperator::fromFilterCondition($condition);
540 $value = ValidatedValue::fromFilterCondition($condition);
541 $this->emit(self::ON_ADD, [$column, $operator, $value]);
542
543 $condition->setColumn($column->getSearchValue());
544 $condition->setValue($value->getSearchValue());
545 $filter->add($condition);
546
547 $changes[$change++] = $column->toTermData();
548 $changes[$change++] = $operator->toTermData();
549 $changes[$change++] = $value->toTermData();
550 }
551
552 $invalid = false;
553 }
554
555 $this->getElement($this->getSearchParameter())
556 ->getAttributes()
557 ->registerAttributeCallback('value', function () {
558 return '';
559 });
560 $this->setFilter($filter);
561
562 if (! empty($changes)) {
563 if (empty($this->changes)) {
564 $this->changes = ['#' . $searchInputId, $changes];
565 } else {
566 $this->changes[1] += $changes;
567 }
568 }
569
570 return ! $invalid;
571 })
572 ]
573 ]);
574 if ($this->getSuggestionUrl() !== null) {
575 $filterInput->getAttributes()->registerAttributeCallback('data-suggest-url', function () {
576 return (string) $this->getSuggestionUrl();
577 });
578 }
579
580 $this->registerElement($filterInput);
581
582 $submitButton = new SubmitElement('submit', ['label' => $this->getSubmitLabel() ?: 'hidden']);
583 $this->registerElement($submitButton);
584
585 $editorOpener = null;
586 if ($this->getEditorUrl() !== null) {
587 $editorOpener = new HtmlElement(
588 'button',
589 Attributes::create([
590 'type' => 'button',
591 'class' => 'search-editor-opener control-button',
592 'title' => t('Adjust Filter')
593 ])->registerAttributeCallback('data-search-editor-url', function () {
594 return (string) $this->getEditorUrl();
595 }),
596 new Icon('cog')
597 );
598 }
599
600 $this->addHtml(
601 new HtmlElement(
602 'button',
603 Attributes::create(['type' => 'button', 'class' => 'search-options']),
604 new Icon('search')
605 ),
606 new HtmlElement(
607 'div',
608 Attributes::create(['class' => 'filter-input-area']),
609 $termContainer,
610 new HtmlElement('label', Attributes::create(['data-label' => '']), $filterInput)
611 ),
612 $dataInput,
613 $termInput,
614 $submitButton,
615 $this->createUidElement(),
616 new HtmlElement('div', Attributes::create([
617 'id' => $suggestionsId,
618 'class' => 'search-suggestions',
619 'data-base-target' => $suggestionsId
620 ]))
621 );
622
623 // Render the editor container outside of this form. It will contain a form as well later on
624 // loaded by XHR and HTML prohibits nested forms. It's style-wise also better...
625 $doc = new HtmlDocument();
626 $this->prependWrapper($doc);
627 $doc->addHtml($this, ...($editorOpener ? [$editorOpener] : []));
628 }
629 }