Debian Codegraph @

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

raw
1 <?php
2
3 namespace ipl\Web\FormElement;
4
5 use ipl\Html\Attributes;
6 use ipl\Html\FormElement\TextElement;
7 use ipl\Html\HtmlElement;
8 use ipl\Web\Url;
9 use ipl\Web\Widget\Icon;
10 use RuntimeException;
11
12 class SuggestionElement extends TextElement
13 {
14 protected $defaultAttributes = [
15 'autocomplete' => 'off',
16 'class' => 'suggestion-element',
17 'data-enrichment-type' => 'completion'
18 ];
19
20 /** @var ?Url URL to fetch suggestions from */
21 protected ?Url $suggestionsUrl = null;
22
23 /**
24 * Get the URL to fetch suggestions from
25 *
26 * @return Url
27 *
28 * @throws RuntimeException if the suggestionsUrl is not set
29 */
30 public function getSuggestionsUrl(): Url
31 {
32 if ($this->suggestionsUrl === null) {
33 throw new RuntimeException('SuggestionsUrl is not set');
34 }
35
36 return $this->suggestionsUrl;
37 }
38
39 /**
40 * Set the URL to fetch suggestions from
41 *
42 * @param Url $suggestionsUrl
43 *
44 * @return $this
45 */
46 public function setSuggestionsUrl(Url $suggestionsUrl): static
47 {
48 $this->suggestionsUrl = $suggestionsUrl;
49
50 return $this;
51 }
52
53 /**
54 * @return string If not set, returns a default placeholder
55 */
56 public function getPlaceholder(): string
57 {
58 return $this->placeholder ?? $this->translate('Start typing to see suggestions…');
59 }
60
61 protected function assemble(): void
62 {
63 $suggestionsId = uniqid('search-suggestions-');
64
65 $this->prependWrapper(
66 new HtmlElement(
67 'div',
68 new Attributes(['class' => 'suggestion-element-group']),
69 new HtmlElement('div', new Attributes(['id' => $suggestionsId, 'class' => 'search-suggestions'])),
70 new HtmlElement('span', new Attributes(['class' => 'suggestion-element-icon']), new Icon('search'))
71 )
72 );
73
74 $this->getAttributes()->add([
75 'data-term-suggestions' => '#' . $suggestionsId,
76 'data-suggest-url' => $this->getSuggestionsUrl()
77 ]);
78 }
79
80 protected function registerAttributeCallbacks(Attributes $attributes): void
81 {
82 parent::registerAttributeCallbacks($attributes);
83
84 $attributes->registerAttributeCallback('suggestionsUrl', null, $this->setSuggestionsUrl(...));
85 }
86 }