Debian Codegraph @

vendor/ipl/web/src/Control/SearchEditor.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\FieldsetElement;
8 use ipl\Html\HtmlDocument;
9 use ipl\Html\HtmlElement;
10 use ipl\I18n\Translation;
11 use ipl\Stdlib\Events;
12 use ipl\Stdlib\Filter;
13 use ipl\Web\Compat\StyleWithNonce;
14 use ipl\Web\Control\SearchBar\SearchException;
15 use ipl\Web\Control\SearchEditor\ConditionErrorsDecorator;
16 use ipl\Web\Filter\Parser;
17 use ipl\Web\Filter\QueryString;
18 use ipl\Web\Filter\Renderer;
19 use ipl\Web\Style;
20 use ipl\Web\Url;
21 use ipl\Web\Widget\IcingaIcon;
22 use ipl\Web\Widget\Icon;
23
24 class SearchEditor extends Form
25 {
26 use Events;
27 use Translation;
28
29 /** @var string Emitted for every validated column */
30 public const ON_VALIDATE_COLUMN = 'validate-column';
31
32 /** @var string The column name used for empty conditions */
33 public const FAKE_COLUMN = '_fake_';
34
35 protected $defaultAttributes = [
36 'data-enrichment-type' => 'search-editor',
37 'class' => 'search-editor'
38 ];
39
40 /** @var string */
41 protected $queryString;
42
43 /** @var Url */
44 protected $suggestionUrl;
45
46 /** @var Parser */
47 protected $parser;
48
49 /** @var Filter\Rule */
50 protected $filter;
51
52 /** @var ?Style */
53 protected ?Style $style = null;
54
55 /** @var bool */
56 protected $cleared = false;
57
58 /**
59 * Set the filter query string to populate the form with
60 *
61 * Use {@see SearchEditor::getParser()} to subscribe to parser events.
62 *
63 * @param string $query
64 *
65 * @return $this
66 */
67 public function setQueryString($query)
68 {
69 $this->queryString = $query;
70
71 return $this;
72 }
73
74 /**
75 * Get the suggestion url
76 *
77 * @return ?Url
78 */
79 public function getSuggestionUrl(): ?Url
80 {
81 return $this->suggestionUrl;
82 }
83
84 /**
85 * Set the suggestion url
86 *
87 * @param Url $url
88 *
89 * @return $this
90 */
91 public function setSuggestionUrl(Url $url)
92 {
93 $this->suggestionUrl = $url;
94
95 return $this;
96 }
97
98 /**
99 * Get the query string parser being used
100 *
101 * @return Parser
102 */
103 public function getParser()
104 {
105 if ($this->parser === null) {
106 $this->parser = new Parser();
107 }
108
109 return $this->parser;
110 }
111
112 /**
113 * Get the current filter
114 *
115 * @return Filter\Rule
116 */
117 public function getFilter()
118 {
119 if ($this->filter === null) {
120 $this->filter = $this->getParser()
121 ->setQueryString($this->queryString)
122 ->parse();
123 }
124
125 return $this->filter;
126 }
127
128 /**
129 * Get inline stylesheet
130 *
131 * @return Style
132 */
133 protected function getStyle(): Style
134 {
135 if ($this->style === null) {
136 $this->style = new StyleWithNonce();
137 }
138
139 return $this->style;
140 }
141
142 public function populate($values)
143 {
144 // applyChanges() is basically this form's own populate implementation, hence
145 // why it changes $values and needs to run before actually populating the form
146 $filter = (new Parser(isset($values['filter']) ? $values['filter'] : $this->queryString))
147 ->setStrict()
148 ->parse();
149 if (! $filter instanceof Filter\Chain) {
150 $filter = Filter::all($filter);
151 }
152
153 $filter = $this->applyChanges($filter, $values);
154
155 parent::populate($values);
156
157 $this->filter = $this->applyStructuralChange($filter);
158 if ($this->filter !== null && ($this->filter instanceof Filter\Condition || ! $this->filter->isEmpty())) {
159 $this->queryString = (new Renderer($this->filter))->setStrict()->render();
160 } else {
161 $this->queryString = '';
162 }
163
164 return $this;
165 }
166
167 public function hasBeenSubmitted()
168 {
169 if (parent::hasBeenSubmitted()) {
170 return true;
171 }
172
173 return $this->cleared;
174 }
175
176 public function validate()
177 {
178 if ($this->cleared) {
179 $this->isValid = true;
180 } else {
181 parent::validate();
182 }
183
184 return $this;
185 }
186
187 protected function applyChanges(Filter\Rule $rule, array &$values, array $path = [0])
188 {
189 $identifier = 'rule-' . join('-', $path);
190
191 if ($rule instanceof Filter\Condition) {
192 $newColumn = $this->popKey($values, $identifier . '-column-search');
193 if ($newColumn === null) {
194 $newColumn = $this->popKey($values, $identifier . '-column');
195 } else {
196 // Make sure we don't forget to present the column labels again
197 $rule->metaData()->set('columnLabel', $this->popKey($values, $identifier . '-column'));
198 }
199
200 if ($newColumn !== null && $rule->getColumn() !== $newColumn) {
201 $rule->setColumn($newColumn ?: static::FAKE_COLUMN);
202 // TODO: Clear meta data?
203 }
204
205 $newValue = $this->popKey($values, $identifier . '-value');
206 $oldValue = $rule->getValue();
207 if ($newValue !== null && $oldValue !== $newValue) {
208 $rule->setValue($newValue);
209 }
210
211 $newOperator = $this->popKey($values, $identifier . '-operator');
212 if ($newOperator !== null && QueryString::getRuleSymbol($rule) !== $newOperator) {
213 $value = $rule->getValue();
214 $column = $rule->getColumn();
215 switch ($newOperator) {
216 case '~':
217 return Filter::like($column, $value);
218 case '!~':
219 return Filter::unlike($column, $value);
220 case '=':
221 return Filter::equal($column, $value);
222 case '!=':
223 return Filter::unequal($column, $value);
224 case '>':
225 return Filter::greaterThan($column, $value);
226 case '>=':
227 return Filter::greaterThanOrEqual($column, $value);
228 case '<':
229 return Filter::lessThan($column, $value);
230 case '<=':
231 return Filter::lessThanOrEqual($column, $value);
232 }
233 }
234
235 $value = $rule->getValue();
236 if ($oldValue !== $value && is_string($value) && strpos($value, '*') !== false) {
237 if (QueryString::getRuleSymbol($rule) === '=') {
238 return Filter::like($rule->getColumn(), $value);
239 } elseif (QueryString::getRuleSymbol($rule) === '!=') {
240 return Filter::unlike($rule->getColumn(), $value);
241 }
242 }
243 } else {
244 /** @var Filter\Chain $rule */
245 $newGroupOperator = $this->popKey($values, $identifier);
246 $oldGroupOperator = $rule instanceof Filter\None ? '!' : QueryString::getRuleSymbol($rule);
247 if ($newGroupOperator !== null && $oldGroupOperator !== $newGroupOperator) {
248 switch ($newGroupOperator) {
249 case '&':
250 $rule = Filter::all(...$rule);
251 break;
252 case '|':
253 $rule = Filter::any(...$rule);
254 break;
255 case '!':
256 $rule = Filter::none(...$rule);
257 break;
258 }
259 }
260
261 $i = 0;
262 foreach ($rule as $child) {
263 $childPath = $path;
264 $childPath[] = $i++;
265 $newChild = $this->applyChanges($child, $values, $childPath);
266 if ($child !== $newChild) {
267 $rule->replace($child, $newChild);
268 }
269 }
270 }
271
272 return $rule;
273 }
274
275 protected function applyStructuralChange(Filter\Rule $rule)
276 {
277 $structuralChange = $this->getPopulatedValue('structural-change');
278 if (empty($structuralChange)) {
279 return $rule;
280 } elseif (is_array($structuralChange)) {
281 ksort($structuralChange);
282 }
283
284 list($type, $where) = explode(':', is_array($structuralChange)
285 ? array_shift($structuralChange)
286 : $structuralChange);
287 $targetPath = explode('-', substr($where, 5));
288
289 $targetFinder = function ($path) use ($rule) {
290 $parent = null;
291 $target = null;
292 $children = [$rule];
293 foreach ($path as $targetPos) {
294 if ($target !== null) {
295 $parent = $target;
296 $children = $parent instanceof Filter\Chain
297 ? iterator_to_array($parent)
298 : [];
299 }
300
301 if (! isset($children[$targetPos])) {
302 return [null, null];
303 }
304
305 $target = $children[$targetPos];
306 }
307
308 return [$parent, $target];
309 };
310
311 list($parent, $target) = $targetFinder($targetPath);
312 if ($target === null) {
313 return $rule;
314 }
315
316 $emptyEqual = Filter::equal(static::FAKE_COLUMN, '');
317 switch ($type) {
318 case 'move-rule':
319 if (! is_array($structuralChange) || empty($structuralChange)) {
320 return $rule;
321 }
322
323 list($placement, $moveToPath) = explode(':', array_shift($structuralChange));
324 list($moveToParent, $moveToTarget) = $targetFinder(explode('-', substr($moveToPath, 5)));
325
326 $parent->remove($target);
327 if ($placement === 'to') {
328 $moveToTarget->add($target);
329 } elseif ($placement === 'before') {
330 $moveToParent->insertBefore($target, $moveToTarget);
331 } else {
332 $moveToParent->insertAfter($target, $moveToTarget);
333 }
334
335 break;
336 case 'add-condition':
337 $target->add($emptyEqual);
338
339 break;
340 case 'add-group':
341 $target->add(Filter::all($emptyEqual));
342
343 break;
344 case 'wrap-rule':
345 if ($parent !== null) {
346 $parent->replace($target, Filter::all($target));
347 } else {
348 $rule = Filter::all($target);
349 }
350
351 break;
352 case 'drop-rule':
353 if ($parent !== null) {
354 $parent->remove($target);
355 } else {
356 $rule = $emptyEqual;
357 }
358
359 break;
360 case 'clear':
361 $this->cleared = true;
362 $rule = null;
363 }
364
365 return $rule;
366 }
367
368 protected function createTree(Filter\Rule $rule, array $path = [0], bool $draggable = false)
369 {
370 $identifier = 'rule-' . join('-', $path);
371
372 if ($rule instanceof Filter\Condition) {
373 $parts = [$this->createCondition($rule, $identifier), $this->createButtons($rule, $identifier)];
374
375 if ($draggable) {
376 array_unshift($parts, new Icon('bars', ['class' => 'drag-initiator']));
377 }
378
379 $item = (new HtmlDocument())->addHtml(...$parts);
380 } else {
381 /** @var Filter\Chain $rule */
382 $item = new HtmlElement('ul');
383
384 $groupOperatorInput = $this->createElement('select', $identifier, [
385 'options' => [
386 '&' => $this->translate('AND'),
387 '|' => $this->translate('OR'),
388 '!' => $this->translate('NOT')
389 ],
390 'value' => $rule instanceof Filter\None ? '!' : QueryString::getRuleSymbol($rule)
391 ]);
392 $this->registerElement($groupOperatorInput);
393 $item->addHtml(HtmlElement::create('li', ['id' => $identifier], [
394 $draggable
395 ? new Icon('bars', ['class' => 'drag-initiator'])
396 : null,
397 $groupOperatorInput,
398 $this->createButtons($rule, $identifier)
399 ]));
400
401 $children = new HtmlElement('ol');
402 $item->addHtml(new HtmlElement('li', null, $children));
403
404 $this->getStyle()->addFor($children, [
405 '--depth' => sprintf('%dem', count($path))
406 ]);
407
408 $i = 0;
409 $draggableChildren = count($path) > 1 || $rule->count() > 1;
410 foreach ($rule as $child) {
411 $childPath = $path;
412 $childPath[] = $i++;
413 $children->addHtml(new HtmlElement(
414 'li',
415 Attributes::create([
416 'id' => 'rule-' . join('-', $childPath),
417 'class' => $child instanceof Filter\Condition
418 ? 'filter-condition'
419 : 'filter-chain'
420 ]),
421 $this->createTree($child, $childPath, $draggableChildren)
422 ));
423 }
424 }
425
426 return $item;
427 }
428
429 protected function createButtons(Filter\Rule $for, $identifier)
430 {
431 $buttons = [];
432
433 if ($for instanceof Filter\Chain) {
434 $buttons[] = $this->createElement('submitButton', 'structural-change', [
435 'value' => 'add-condition:' . $identifier,
436 'title' => $this->translate('Append Condition', 'to a group of filter conditions'),
437 'label' => new IcingaIcon('add-inside'),
438 'class' => 'control-button',
439 'formnovalidate' => true
440 ]);
441 $buttons[] = $this->createElement('submitButton', 'structural-change', [
442 'value' => 'add-group:' . $identifier,
443 'title' => $this->translate('Append Group', 'of filter conditions'),
444 'label' => new IcingaIcon('insert-group'),
445 'class' => 'control-button',
446 'formnovalidate' => true
447 ]);
448
449 $wrapTitle = $this->translate('Wrap Group in Group', 'of filter conditions');
450 $removeTitle = $this->translate('Remove Group', 'of filter conditions');
451 } else {
452 $wrapTitle = $this->translate('Wrap Condition in Group', 'a filter rule');
453 $removeTitle = $this->translate('Remove Condition', 'a filter rule');
454 }
455
456 $buttons[] = $this->createElement('submitButton', 'structural-change', [
457 'value' => 'wrap-rule:' . $identifier,
458 'label' => new IcingaIcon('wrap'),
459 'class' => 'control-button',
460 'title' => $wrapTitle,
461 'formnovalidate' => true
462 ]);
463 $buttons[] = $this->createElement('submitButton', 'structural-change', [
464 'value' => 'drop-rule:' . $identifier,
465 'label' => new Icon('trash'),
466 'class' => ['control-button', 'remove-button'],
467 'title' => $removeTitle,
468 'formnovalidate' => true
469 ]);
470
471 $ul = new HtmlElement('ul', Attributes::create(['class' => 'buttons']));
472 foreach ($buttons as $button) {
473 $ul->addHtml(new HtmlElement('li', null, $button));
474 }
475
476 return $ul;
477 }
478
479 protected function createCondition(Filter\Condition $condition, $identifier)
480 {
481 $columnInput = $this->createElement('text', $identifier . '-column', [
482 'value' => $condition->metaData()->get(
483 'columnLabel',
484 $condition->getColumn() !== static::FAKE_COLUMN
485 ? $condition->getColumn()
486 : null
487 ),
488 'title' => $condition->getColumn() !== static::FAKE_COLUMN
489 ? $condition->getColumn()
490 : null,
491 'required' => true,
492 'autocomplete' => 'off',
493 'data-type' => 'column',
494 'data-enrichment-type' => 'completion',
495 'data-term-suggestions' => '#search-editor-suggestions',
496 'placeholder' => $this->getSuggestionUrl() !== null
497 ? $this->translate('Start typing to search for a column')
498 : null
499 ]);
500 $columnInput->getAttributes()->registerAttributeCallback('data-suggest-url', function () {
501 return (string) $this->getSuggestionUrl();
502 });
503
504 $columnFakeInput = $this->createElement('hidden', $identifier . '-column-search', [
505 'value' => static::FAKE_COLUMN
506 ]);
507 $columnSearchInput = $this->createElement('hidden', $identifier . '-column-search', [
508 'value' => $condition->getColumn() !== static::FAKE_COLUMN
509 ? $condition->getColumn()
510 : null,
511 'validators' => ['Callback' => function ($value) use ($condition, $columnInput, &$columnSearchInput) {
512 if (! $this->hasBeenSubmitted()) {
513 return true;
514 }
515
516 try {
517 $this->emit(static::ON_VALIDATE_COLUMN, [$condition]);
518 } catch (SearchException $e) {
519 $columnInput->addMessage($e->getMessage());
520 if (trim($columnInput->getValue())) {
521 $columnInput->getAttributes()->add(
522 'pattern',
523 sprintf('^\s*(?!%s\b).*\s*$', $columnInput->getValue())
524 );
525 }
526
527 return false;
528 }
529
530 $columnSearchInput->setValue($condition->getColumn());
531 $columnInput->setValue($condition->metaData()->get('columnLabel', $condition->getColumn()));
532
533 return true;
534 }]
535 ]);
536
537 $operatorInput = $this->createElement('select', $identifier . '-operator', [
538 'options' => [
539 '~' => '~',
540 '!~' => '!~',
541 '=' => '=',
542 '!=' => '!=',
543 '>' => '>',
544 '<' => '<',
545 '>=' => '>=',
546 '<=' => '<='
547 ],
548 'value' => QueryString::getRuleSymbol($condition)
549 ]);
550
551 $valueInput = $this->createElement('text', $identifier . '-value', [
552 'value' => $condition->getValue(),
553 'autocomplete' => 'off',
554 'data-type' => 'value',
555 'data-enrichment-type' => 'completion',
556 'data-term-suggestions' => '#search-editor-suggestions',
557 'placeholder' => $this->getSuggestionUrl() !== null
558 ? $this->translate('Start typing to search for a value')
559 : null
560 ]);
561 $valueInput->getAttributes()->registerAttributeCallback('data-suggest-url', function () {
562 return (string) $this->getSuggestionUrl();
563 });
564
565 $this->registerElement($columnInput);
566 $this->registerElement($columnSearchInput);
567 $this->registerElement($operatorInput);
568 $this->registerElement($valueInput);
569
570 $fieldset = (new FieldsetElement($identifier . '-'))
571 ->addHtml(
572 $columnInput,
573 $columnFakeInput,
574 $columnSearchInput,
575 $operatorInput,
576 $valueInput
577 )
578 ->setDecorators(['errors' => new ConditionErrorsDecorator()]);
579
580 $this->decorate($fieldset);
581
582 return $fieldset;
583 }
584
585 protected function assemble()
586 {
587 $this->addHtml($this->getStyle());
588
589 $filterInput = $this->createElement('hidden', 'filter');
590 $filterInput->getAttributes()->registerAttributeCallback(
591 'value',
592 function () {
593 return $this->queryString ?: static::FAKE_COLUMN;
594 },
595 [$this, 'setQueryString']
596 );
597 $this->addElement($filterInput);
598
599 $filter = $this->getFilter();
600 if ($filter instanceof Filter\Chain) {
601 if ($filter->isEmpty()) {
602 $filter = Filter::all(Filter::equal('', ''));
603 }
604 } else {
605 $filter = Filter::all($filter);
606 }
607
608 $this->addHtml($this->createTree($filter));
609 $this->addHtml(new HtmlElement('div', Attributes::create([
610 'id' => 'search-editor-suggestions',
611 'class' => 'search-suggestions'
612 ])));
613
614 $this->addHtml($this->createElement('submitButton', 'structural-change', [
615 'value' => 'clear:rule-0',
616 'class' => 'cancel-button',
617 'label' => $this->translate('Clear Filter'),
618 'formnovalidate' => true
619 ]));
620
621 $this->addElement('submit', 'btn_submit', [
622 'label' => $this->translate('Apply')
623 ]);
624
625 // Add submit button also as first element to make Web 2 submit
626 // the form instead of using a structural change to submit if
627 // the user just presses Enter.
628 $this->prepend($this->getElement('btn_submit'));
629 }
630
631 private function popKey(array &$from, $key, $default = null)
632 {
633 if (isset($from[$key])) {
634 $value = $from[$key];
635 unset($from[$key]);
636
637 return $value;
638 }
639
640 return $default;
641 }
642 }