Debian Codegraph @

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

raw
1 <?php
2
3 namespace ipl\Web\Control\SearchBar;
4
5 use Countable;
6 use Generator;
7 use ipl\Html\Attributes;
8 use ipl\Html\BaseHtmlElement;
9 use ipl\Html\FormattedString;
10 use ipl\Html\FormElement\ButtonElement;
11 use ipl\Html\HtmlElement;
12 use ipl\Html\Text;
13 use ipl\Stdlib\Contract\Paginatable;
14 use ipl\Stdlib\Filter;
15 use ipl\Web\Control\SearchEditor;
16 use ipl\Web\Filter\QueryString;
17 use IteratorIterator;
18 use LimitIterator;
19 use OuterIterator;
20 use Psr\Http\Message\ServerRequestInterface;
21 use Traversable;
22
23 use function ipl\I18n\t;
24
25 abstract class Suggestions extends BaseHtmlElement
26 {
27 public const DEFAULT_LIMIT = 50;
28 public const SUGGESTION_TITLE_CLASS = 'suggestion-title';
29
30 protected $tag = 'ul';
31
32 /** @var string */
33 protected $searchTerm;
34
35 /** @var Traversable */
36 protected $data;
37
38 /** @var array */
39 protected $default;
40
41 /** @var string */
42 protected $type;
43
44 /** @var string */
45 protected $failureMessage;
46
47 public function setSearchTerm($term)
48 {
49 $this->searchTerm = $term;
50
51 return $this;
52 }
53
54 public function setData($data)
55 {
56 $this->data = $data;
57
58 return $this;
59 }
60
61 public function setDefault($default)
62 {
63 $this->default = $default;
64
65 return $this;
66 }
67
68 public function setType($type)
69 {
70 $this->type = $type;
71
72 return $this;
73 }
74
75 public function setFailureMessage($message)
76 {
77 $this->failureMessage = $message;
78
79 return $this;
80 }
81
82 /**
83 * Return whether the relation should be shown for the given column
84 *
85 * @param string $column
86 *
87 * @return bool
88 */
89 protected function shouldShowRelationFor(string $column): bool
90 {
91 return false;
92 }
93
94 /**
95 * Create a filter to provide as default for column suggestions
96 *
97 * @param string $searchTerm
98 *
99 * @return Filter\Rule
100 */
101 abstract protected function createQuickSearchFilter($searchTerm);
102
103 /**
104 * Fetch value suggestions for a particular column
105 *
106 * @param string $column
107 * @param string $searchTerm
108 * @param Filter\Chain $searchFilter
109 *
110 * @return Traversable
111 */
112 abstract protected function fetchValueSuggestions($column, $searchTerm, Filter\Chain $searchFilter);
113
114 /**
115 * Fetch column suggestions
116 *
117 * @param string $searchTerm
118 *
119 * @return Traversable
120 */
121 abstract protected function fetchColumnSuggestions($searchTerm);
122
123 protected function filterToTerms(Filter\Chain $filter)
124 {
125 $logicalSep = [
126 'label' => QueryString::getRuleSymbol($filter),
127 'search' => QueryString::getRuleSymbol($filter),
128 'class' => 'logical-operator',
129 'type' => 'logical_operator'
130 ];
131
132 $terms = [];
133 foreach ($filter as $child) {
134 if ($child instanceof Filter\Chain) {
135 $terms[] = [
136 'search' => '(',
137 'label' => '(',
138 'type' => 'grouping_operator',
139 'class' => 'grouping-operator-open'
140 ];
141 $terms = array_merge($terms, $this->filterToTerms($child));
142 $terms[] = [
143 'search' => ')',
144 'label' => ')',
145 'type' => 'grouping_operator',
146 'class' => 'grouping-operator-close'
147 ];
148 } else {
149 /** @var Filter\Condition $child */
150
151 $terms[] = [
152 'search' => $child->getColumn(),
153 'label' => $child->metaData()->get('columnLabel') ?? $child->getColumn(),
154 'type' => 'column'
155 ];
156 $terms[] = [
157 'search' => QueryString::getRuleSymbol($child),
158 'label' => QueryString::getRuleSymbol($child),
159 'type' => 'operator'
160 ];
161 $terms[] = [
162 'search' => $child->getValue(),
163 'label' => $child->getValue(),
164 'type' => 'value'
165 ];
166 }
167
168 $terms[] = $logicalSep;
169 }
170
171 array_pop($terms);
172 return $terms;
173 }
174
175 protected function assembleDefault()
176 {
177 if ($this->default === null) {
178 return;
179 }
180
181 $attributes = [
182 'type' => 'button',
183 'tabindex' => -1,
184 'data-label' => $this->default['search'],
185 'value' => $this->default['search']
186 ];
187 if (isset($this->default['type'])) {
188 $attributes['data-type'] = $this->default['type'];
189 } elseif ($this->type !== null) {
190 $attributes['data-type'] = $this->type;
191 }
192
193 $button = new ButtonElement('', $attributes);
194 if (isset($this->default['type']) && $this->default['type'] === 'terms') {
195 $terms = $this->filterToTerms($this->default['terms']);
196 $list = new HtmlElement('ul', Attributes::create(['class' => 'comma-separated']));
197 foreach ($terms as $data) {
198 if ($data['type'] === 'column') {
199 $list->addHtml(new HtmlElement(
200 'li',
201 null,
202 new HtmlElement('em', null, Text::create($data['label']))
203 ));
204 }
205 }
206
207 $button->setAttribute('data-terms', json_encode($terms));
208 $button->addHtml(FormattedString::create(
209 t('Search for %s in: %s'),
210 new HtmlElement('em', null, Text::create($this->default['search'])),
211 $list
212 ));
213 } else {
214 $button->addHtml(FormattedString::create(
215 t('Search for %s'),
216 new HtmlElement('em', null, Text::create($this->default['search']))
217 ));
218 }
219
220 $this->prependHtml(new HtmlElement('li', Attributes::create(['class' => 'default']), $button));
221 }
222
223 /**
224 * Assemble the list content
225 *
226 * @return bool Whether the default suggestion should be hidden or not
227 */
228 protected function assembleSuggestions(): bool
229 {
230 if ($this->data === null) {
231 $data = [];
232 } elseif ($this->data instanceof Paginatable) {
233 $this->data->limit(self::DEFAULT_LIMIT);
234 $data = $this->data;
235 } else {
236 $data = new LimitIterator(new IteratorIterator($this->data), 0, self::DEFAULT_LIMIT);
237 }
238
239 $noDefault = null;
240 foreach ($data as $term => $meta) {
241 if (is_int($term)) {
242 $term = $meta;
243 }
244
245 if ($this->searchTerm) {
246 // Only the first exact match will set this to true, any other to false
247 $noDefault = $noDefault === null && $term === $this->searchTerm;
248 }
249
250 $attributes = [
251 'type' => 'button',
252 'tabindex' => -1,
253 'data-search' => $term,
254 'data-title' => $term
255 ];
256 if ($this->type !== null) {
257 $attributes['data-type'] = $this->type;
258 }
259
260 if (is_array($meta)) {
261 foreach ($meta as $key => $value) {
262 if ($key === 'label') {
263 $label = $value;
264 }
265
266 $attributes['data-' . $key] = $value;
267 }
268 } else {
269 $label = $meta;
270 $attributes['data-label'] = $meta;
271 }
272
273 $button = (new ButtonElement('', $attributes))
274 ->setAttribute('value', $label)
275 ->addHtml(Text::create($label));
276 if ($this->type === 'column' && $this->shouldShowRelationFor($term)) {
277 $relationPath = substr($term, 0, strrpos($term, '.'));
278 $button->getAttributes()->add('class', 'has-details');
279 $button->addHtml(new HtmlElement(
280 'span',
281 Attributes::create(['class' => 'relation-path']),
282 Text::create($relationPath)
283 ));
284 }
285
286 $this->addHtml(new HtmlElement('li', null, $button));
287 }
288
289 return $noDefault ?? false;
290 }
291
292 protected function assemble()
293 {
294 if ($this->failureMessage === null) {
295 try {
296 $noDefault = $this->assembleSuggestions();
297 } catch (SearchException $e) {
298 $this->failureMessage = $e->getMessage();
299 $this->setContent(null);
300 }
301 }
302
303 if ($this->failureMessage !== null) {
304 $this->addHtml(new HtmlElement(
305 'li',
306 Attributes::create(['class' => 'failure-message']),
307 new HtmlElement('em', null, Text::create(t('Can\'t search:'))),
308 Text::create($this->failureMessage)
309 ));
310 return;
311 }
312
313 if ($this->type === 'column' && ! $this->isEmpty() && ! $this->getFirst('li')->getAttributes()->has('class')) {
314 // The column title is only added if there are any suggestions and the first item is not a title already
315 $this->prependHtml(new HtmlElement(
316 'li',
317 Attributes::create(['class' => static::SUGGESTION_TITLE_CLASS]),
318 Text::create(t('Columns'))
319 ));
320 }
321
322 if (! $noDefault) {
323 $this->assembleDefault();
324 }
325
326 if (! $this->searchTerm && $this->isEmpty()) {
327 $this->addHtml(new HtmlElement(
328 'li',
329 Attributes::create(['class' => 'nothing-to-suggest']),
330 new HtmlElement('em', null, Text::create(t('Nothing to suggest')))
331 ));
332 }
333 }
334
335 /**
336 * Load suggestions as requested by the client
337 *
338 * @param ServerRequestInterface $request
339 *
340 * @return $this
341 */
342 public function forRequest(ServerRequestInterface $request)
343 {
344 if ($request->getMethod() !== 'POST') {
345 return $this;
346 }
347
348 $requestData = json_decode($request->getBody()->read(8192), true);
349 if (empty($requestData)) {
350 return $this;
351 }
352
353 $search = $requestData['term']['search'];
354 $label = $requestData['term']['label'];
355 $type = $requestData['term']['type'];
356
357 $this->setSearchTerm($search);
358 $this->setType($type);
359
360 switch ($type) {
361 case 'value':
362 if (! $requestData['column'] || $requestData['column'] === SearchEditor::FAKE_COLUMN) {
363 $this->setFailureMessage(t('Missing column name'));
364 break;
365 }
366
367 $searchFilter = QueryString::parse(
368 isset($requestData['searchFilter'])
369 ? $requestData['searchFilter']
370 : ''
371 );
372 if ($searchFilter instanceof Filter\Condition) {
373 $searchFilter = Filter::all($searchFilter);
374 }
375
376 try {
377 $this->setData($this->fetchValueSuggestions($requestData['column'], $label, $searchFilter));
378 } catch (SearchException $e) {
379 $this->setFailureMessage($e->getMessage());
380 }
381
382 if ($search) {
383 $this->setDefault([
384 'search' => $requestData['operator'] === '~' || $requestData['operator'] === '!~'
385 ? $label
386 : $search
387 ]);
388 }
389
390 break;
391 case 'column':
392 $this->setData($this->filterColumnSuggestions($this->fetchColumnSuggestions($label), $label));
393
394 if ($search && isset($requestData['showQuickSearch']) && $requestData['showQuickSearch']) {
395 $quickFilter = $this->createQuickSearchFilter($label);
396 if (! $quickFilter instanceof Filter\Chain || ! $quickFilter->isEmpty()) {
397 $this->setDefault([
398 'search' => $label,
399 'type' => 'terms',
400 'terms' => $quickFilter
401 ]);
402 }
403 }
404 }
405
406 return $this;
407 }
408
409 protected function hasMore($data, $than)
410 {
411 if (is_array($data)) {
412 return count($data) > $than;
413 } elseif ($data instanceof Countable) {
414 return $data->count() > $than;
415 } elseif ($data instanceof OuterIterator) {
416 return $this->hasMore($data->getInnerIterator(), $than);
417 }
418
419 return false;
420 }
421
422 /**
423 * Filter the given suggestions by the client's input
424 *
425 * @param Traversable $data
426 * @param string $searchTerm
427 *
428 * @return Generator
429 */
430 protected function filterColumnSuggestions($data, $searchTerm)
431 {
432 foreach ($data as $key => $value) {
433 if ($this->matchSuggestion($key, $value, $searchTerm)) {
434 yield $key => $value;
435 }
436 }
437 }
438
439 /**
440 * Get whether the given suggestion should be provided to the client
441 *
442 * @param string $path
443 * @param string $label
444 * @param string $searchTerm
445 *
446 * @return bool
447 */
448 protected function matchSuggestion($path, $label, $searchTerm)
449 {
450 return fnmatch($searchTerm, $label, FNM_CASEFOLD) || fnmatch($searchTerm, $path, FNM_CASEFOLD);
451 }
452
453 public function renderUnwrapped()
454 {
455 $this->ensureAssembled();
456
457 if ($this->isEmpty()) {
458 return '';
459 }
460
461 return parent::renderUnwrapped();
462 }
463 }