Debian Codegraph @

vendor/ipl/web/src/FormElement/TermInput.php

raw
1 <?php
2
3 namespace ipl\Web\FormElement;
4
5 use ipl\Html\Attribute;
6 use ipl\Html\Attributes;
7 use ipl\Html\Form;
8 use ipl\Html\FormElement\FieldsetElement;
9 use ipl\Html\FormElement\HiddenElement;
10 use ipl\Html\HtmlElement;
11 use ipl\Html\HtmlString;
12 use ipl\Stdlib\Events;
13 use ipl\Web\FormElement\TermInput\RegisteredTerm;
14 use ipl\Web\FormElement\TermInput\TermContainer;
15 use ipl\Web\FormElement\TermInput\ValidatedTerm;
16 use ipl\Web\Url;
17 use Psr\Http\Message\ServerRequestInterface;
18
19 class TermInput extends FieldsetElement
20 {
21 use Events;
22
23 /** @var string Emitted in case the user added new terms */
24 public const ON_ADD = 'on_add';
25
26 /** @var string Emitted in case the user inserted new terms */
27 public const ON_PASTE = 'on_paste';
28
29 /** @var string Emitted in case the user changed existing terms */
30 public const ON_SAVE = 'on_save';
31
32 /** @var string Emitted in case the user removed terms */
33 public const ON_REMOVE = 'on_remove';
34
35 /** @var string Emitted in case terms need to be enriched */
36 public const ON_ENRICH = 'on_enrich';
37
38 /** @var Url The suggestion url */
39 protected $suggestionUrl;
40
41 /** @var bool Whether term direction is vertical */
42 protected $verticalTermDirection = false;
43
44 /** @var bool Whether term order is significant */
45 protected $ordered = false;
46
47 /** @var bool Whether registered terms are read-only */
48 protected $readOnly = false;
49
50 /** @var array Changes to transmit to the client */
51 protected $changes = [];
52
53 /** @var RegisteredTerm[] The terms */
54 protected $terms = [];
55
56 /** @var bool Whether this input has been automatically submitted */
57 private $hasBeenAutoSubmitted = false;
58
59 /** @var bool Whether the term input value has been pasted */
60 private $valueHasBeenPasted;
61
62 /** @var TermContainer The term container */
63 protected $termContainer;
64
65 /**
66 * Set the suggestion url
67 *
68 * @param Url $url
69 *
70 * @return $this
71 */
72 public function setSuggestionUrl(Url $url): self
73 {
74 $this->suggestionUrl = $url;
75
76 return $this;
77 }
78
79 /**
80 * Get the suggestion url
81 *
82 * @return ?Url
83 */
84 public function getSuggestionUrl(): ?Url
85 {
86 return $this->suggestionUrl;
87 }
88
89 /**
90 * Set whether term direction should be vertical
91 *
92 * @param bool $state
93 *
94 * @return $this
95 */
96 public function setVerticalTermDirection(bool $state = true): self
97 {
98 $this->verticalTermDirection = $state;
99
100 return $this;
101 }
102
103 /**
104 * Get the desired term direction
105 *
106 * @return ?string
107 */
108 public function getTermDirection(): ?string
109 {
110 return $this->verticalTermDirection || $this->ordered ? 'vertical' : null;
111 }
112
113 /**
114 * Set whether term order is significant
115 *
116 * @param bool $state
117 *
118 * @return $this
119 */
120 public function setOrdered(bool $state = true): self
121 {
122 $this->ordered = $state;
123
124 return $this;
125 }
126
127 /**
128 * Get whether term order is significant
129 *
130 * @return bool
131 */
132 public function getOrdered(): bool
133 {
134 return $this->ordered;
135 }
136
137 /**
138 * Set whether registered terms are read-only
139 *
140 * @param bool $state
141 *
142 * @return $this
143 */
144 public function setReadOnly(bool $state = true): self
145 {
146 $this->readOnly = $state;
147
148 return $this;
149 }
150
151 /**
152 * Get whether registered terms are read-only
153 *
154 * @return bool
155 */
156 public function getReadOnly(): bool
157 {
158 return $this->readOnly;
159 }
160
161 /**
162 * Set terms
163 *
164 * @param RegisteredTerm ...$terms
165 *
166 * @return $this
167 */
168 public function setTerms(RegisteredTerm ...$terms): self
169 {
170 $this->terms = $terms;
171
172 return $this;
173 }
174
175 /**
176 * Get the terms
177 *
178 * @return RegisteredTerm[]
179 */
180 public function getTerms(): array
181 {
182 return $this->terms;
183 }
184
185 public function getElements()
186 {
187 // TODO: Only a quick-fix. Remove once fieldsets are properly partially validated
188 $this->ensureAssembled();
189
190 return parent::getElements();
191 }
192
193 public function getValue($name = null, $default = null)
194 {
195 if ($name !== null) {
196 return parent::getValue($name, $default);
197 }
198
199 $terms = [];
200 foreach ($this->getTerms() as $term) {
201 $terms[] = $term->render(',');
202 }
203
204 return implode(',', $terms);
205 }
206
207 public function setValue($value)
208 {
209 $separatedTerms = $value;
210 if (is_array($value)) {
211 $separatedTerms = $value['value'] ?? '';
212 parent::setValue($value);
213 }
214
215 $terms = [];
216 foreach ($this->parseValue((string) $separatedTerms) as $term) {
217 $terms[] = new RegisteredTerm($term);
218 }
219
220 return $this->setTerms(...$terms);
221 }
222
223 /**
224 * Parse the given separated string of terms
225 *
226 * @param string $value
227 *
228 * @return string[]
229 */
230 public function parseValue(string $value): array
231 {
232 $terms = [];
233
234 $term = '';
235 $ignoreSeparator = false;
236 for ($i = 0; $i <= strlen($value); $i++) {
237 if (! isset($value[$i])) {
238 if (! empty($term)) {
239 $terms[] = rawurldecode($term);
240 }
241
242 break;
243 }
244
245 $c = $value[$i];
246 if ($c === '"') {
247 $ignoreSeparator = ! $ignoreSeparator;
248 } elseif (! $ignoreSeparator && $c === ',') {
249 $terms[] = rawurldecode($term);
250 $term = '';
251 } else {
252 $term .= $c;
253 }
254 }
255
256 return $terms;
257 }
258
259 /**
260 * Prepare updates to transmit for this input during multipart responses
261 *
262 * @param ServerRequestInterface $request
263 *
264 * @return array
265 */
266 public function prepareMultipartUpdate(ServerRequestInterface $request): array
267 {
268 $updates = [];
269 if ($this->valueHasBeenPasted()) {
270 $updates[] = $this->termContainer();
271 $updates[] = [
272 HtmlString::create(json_encode(
273 ['#' . Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-search-input', []]
274 )),
275 'Behavior:InputEnrichment'
276 ];
277 } elseif (! empty($this->changes)) {
278 $updates[] = [
279 HtmlString::create(json_encode(
280 ['#' . Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-search-input', $this->changes]
281 )),
282 'Behavior:InputEnrichment'
283 ];
284 }
285
286 if (empty($updates) && $this->hasBeenAutoSubmitted()) {
287 $updates[] = $updates[] = [
288 HtmlString::create(json_encode(
289 ['#' . Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-search-input', 'bogus']
290 )),
291 'Behavior:InputEnrichment'
292 ];
293 }
294
295 return $updates;
296 }
297
298 /**
299 * Get whether this input has been automatically submitted
300 *
301 * @return bool
302 */
303 private function hasBeenAutoSubmitted(): bool
304 {
305 return $this->hasBeenAutoSubmitted;
306 }
307
308 /**
309 * Get whether the term input value has been pasted
310 *
311 * @return bool
312 */
313 private function valueHasBeenPasted(): bool
314 {
315 if ($this->valueHasBeenPasted === null) {
316 $this->valueHasBeenPasted = ($this->getElement('data')->getValue()['type'] ?? null) === 'paste';
317 }
318
319 return $this->valueHasBeenPasted;
320 }
321
322 public function onRegistered(Form $form)
323 {
324 $termContainerId = Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-terms';
325 $mainInputId = Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-search-input';
326 $autoSubmittedBy = $form->getRequest()->getHeader('X-Icinga-Autosubmittedby');
327
328 $this->hasBeenAutoSubmitted = in_array($mainInputId, $autoSubmittedBy, true)
329 || in_array($termContainerId, $autoSubmittedBy, true);
330
331 parent::onRegistered($form);
332 }
333
334 /**
335 * Validate the given terms
336 *
337 * @param string $type The type of change to validate
338 * @param array $terms The terms affected by the change
339 * @param array $changes Potential changes made by validators
340 *
341 * @return bool
342 */
343 private function validateTerms(string $type, array $terms, array &$changes): bool
344 {
345 $validatedTerms = [];
346 foreach ($terms as $index => $data) {
347 $validatedTerms[$index] = ValidatedTerm::fromTermData($data);
348 }
349
350 switch ($type) {
351 case 'submit':
352 case 'exchange':
353 $type = self::ON_ADD;
354
355 break;
356 case 'paste':
357 $type = self::ON_PASTE;
358
359 break;
360 case 'save':
361 $type = self::ON_SAVE;
362
363 break;
364 case 'remove':
365 default:
366 return true;
367 }
368
369 $this->emit($type, [$validatedTerms]);
370
371 $invalid = false;
372 foreach ($validatedTerms as $index => $term) {
373 if (! $term->isValid()) {
374 $invalid = true;
375 }
376
377 if (! $term->isValid() || $term->hasBeenChanged()) {
378 $changes[$index] = $term->toTermData();
379 }
380 }
381
382 return $invalid;
383 }
384
385 /**
386 * Get the term container
387 *
388 * @return TermContainer
389 */
390 protected function termContainer(): TermContainer
391 {
392 if ($this->termContainer === null) {
393 $this->termContainer = (new TermContainer($this))
394 ->setAttribute('id', Attribute::sanitizeId($this->getValueOfNameAttribute()) . '-terms');
395 }
396
397 return $this->termContainer;
398 }
399
400 protected function assemble()
401 {
402 $myName = Attribute::sanitizeId($this->getValueOfNameAttribute());
403
404 $termInputId = $myName . '-term-input';
405 $dataInputId = $myName . '-data-input';
406 $searchInputId = $myName . '-search-input';
407 $suggestionsId = $myName . '-suggestions';
408
409 $termContainer = $this->termContainer();
410
411 $suggestions = (new HtmlElement('div'))
412 ->setAttribute('id', $suggestionsId)
413 ->setAttribute('class', 'search-suggestions');
414
415 $termInput = $this->createElement('hidden', 'value', [
416 'id' => $termInputId,
417 'disabled' => true
418 ]);
419
420 $dataInput = new class ('data', [
421 'ignore' => true,
422 'id' => $dataInputId,
423 'validators' => ['callback' => function ($data) use ($termContainer) {
424 $changes = [];
425 $invalid = $this->validateTerms($data['type'], $data['terms'] ?? [], $changes);
426 $this->changes = $changes;
427
428 $terms = $this->getTerms();
429 foreach ($changes as $index => $termData) {
430 $terms[$index]->applyTermData($termData);
431 }
432
433 return ! $invalid;
434 }]
435 ]) extends HiddenElement {
436 /** @var TermInput */
437 private $parent;
438
439 public function setParent(TermInput $parent): void
440 {
441 $this->parent = $parent;
442 }
443
444 public function setValue($value)
445 {
446 $data = json_decode($value, true);
447 if (($data['type'] ?? null) === 'paste') {
448 array_push($data['terms'], ...array_map(function ($t) {
449 return ['search' => $t];
450 }, $this->parent->parseValue($data['input'])));
451 }
452
453 return parent::setValue($data);
454 }
455
456 public function getValueAttribute()
457 {
458 return null;
459 }
460 };
461 $dataInput->setParent($this);
462
463 $label = $this->getLabel();
464 $this->setLabel(null);
465
466 // TODO: Separator customization
467 $mainInput = $this->createElement('text', 'value', [
468 'id' => $searchInputId,
469 'label' => $label,
470 'required' => $this->isRequired(),
471 'placeholder' => $this->translate('Type to search. Separate multiple terms by comma.'),
472 'class' => 'term-input',
473 'autocomplete' => 'off',
474 'data-term-separator' => ',',
475 'data-enrichment-type' => 'terms',
476 'data-with-multi-completion' => true,
477 'data-no-auto-submit-on-remove' => true,
478 'data-term-direction' => $this->getTermDirection(),
479 'data-maintain-term-order' => $this->getOrdered() && ! $this->getAttribute('disabled')->getValue(),
480 'data-read-only-terms' => $this->getReadOnly(),
481 'data-data-input' => '#' . $dataInputId,
482 'data-term-input' => '#' . $termInputId,
483 'data-term-container' => '#' . $termContainer->getAttribute('id')->getValue(),
484 'data-term-suggestions' => '#' . $suggestionsId
485 ]);
486 $mainInput->getAttributes()
487 ->registerAttributeCallback('value', function () {
488 return null;
489 });
490 if ($this->getSuggestionUrl() !== null) {
491 $mainInput->getAttributes()->registerAttributeCallback('data-suggest-url', function () {
492 return (string) $this->getSuggestionUrl();
493 });
494 }
495
496 $this->addElement($termInput);
497 $this->addElement($dataInput);
498 $this->addElement($mainInput);
499
500 $mainInput->prependWrapper((new HtmlElement(
501 'div',
502 Attributes::create(['class' => [
503 'term-input-area',
504 $this->getTermDirection(),
505 $this->getReadOnly() ? 'read-only' : null
506 ]]),
507 $termContainer,
508 new HtmlElement('label', null, $mainInput)
509 )));
510
511 $this->addHtml($suggestions);
512
513 if (! $this->hasBeenAutoSubmitted()) {
514 $this->emit(self::ON_ENRICH, [$this->getTerms()]);
515 }
516 }
517 }