summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/web/src/FormElement/TermInput/TermSuggestions.php
blob: 26b00eac83e62a12326d4a90e8c48ac1c08ac86d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php

namespace ipl\Web\FormElement\TermInput;

use ipl\Html\Attributes;
use ipl\Html\BaseHtmlElement;
use ipl\Html\HtmlElement;
use ipl\Html\Text;
use ipl\I18n\Translation;
use Psr\Http\Message\ServerRequestInterface;
use Traversable;

use function ipl\Stdlib\yield_groups;

class TermSuggestions extends BaseHtmlElement
{
    use Translation;

    protected $tag = 'ul';

    /** @var Traversable */
    protected $provider;

    /** @var ?callable */
    protected $groupingCallback;

    /** @var ?string */
    protected $searchTerm;

    /** @var ?string */
    protected $searchPattern;

    /** @var ?string */
    protected $originalValue;

    /** @var string[] */
    protected $excludeTerms = [];

    /**
     * Create new TermSuggestions
     *
     * The provider must deliver terms in form of arrays with the following keys:
     * * (required) search: The search value
     * * label: A human-readable label
     * * class: A CSS class
     * * title: A message shown upon hover on the term
     *
     * Any excess key is also transferred to the client, but currently unused.
     *
     * @param Traversable $provider
     */
    public function __construct(Traversable $provider)
    {
        $this->provider = $provider;
    }

    /**
     * Set a callback to identify groups for terms delivered by the provider
     *
     * The callback must return a string which is used as label for the group.
     * Its interface is: `function (array $data): string`
     *
     * @param callable $callback
     *
     * @return $this
     */
    public function setGroupingCallback(callable $callback): self
    {
        $this->groupingCallback = $callback;

        return $this;
    }

    /**
     * Get the callback used to identify groups for terms delivered by the provider
     *
     * @return ?callable
     */
    public function getGroupingCallback(): ?callable
    {
        return $this->groupingCallback;
    }

    /**
     * Set the search term (can contain `*` wildcards)
     *
     * @param string $term
     *
     * @return $this
     */
    public function setSearchTerm(string $term): self
    {
        $this->searchTerm = $term;
        $this->setSearchPattern(
            '/' . str_replace(
                '\\000',
                '.*',
                preg_quote(
                    str_replace(
                        '*',
                        "\0",
                        $term
                    ),
                    '/'
                )
            ) . '/i'
        );

        return $this;
    }

    /**
     * Get the search term
     *
     * @return ?string
     */
    public function getSearchTerm(): ?string
    {
        return $this->searchTerm;
    }

    /**
     * Set the search pattern used by {@see matchSearch}
     *
     * @param string $pattern
     *
     * @return $this
     */
    protected function setSearchPattern(string $pattern): self
    {
        $this->searchPattern = $pattern;

        return $this;
    }

    /**
     * Set the original search value
     *
     * The one without automatically added wildcards.
     *
     * @param string $term
     *
     * @return $this
     */
    public function setOriginalSearchValue(string $term): self
    {
        $this->originalValue = $term;

        return $this;
    }

    /**
     * Get the original search value
     *
     * @return ?string
     */
    public function getOriginalSearchValue(): ?string
    {
        return $this->originalValue;
    }

    /**
     * Set the terms to exclude in the suggestion list
     *
     * @param string[] $terms
     *
     * @return $this
     */
    public function setExcludeTerms(array $terms): self
    {
        $this->excludeTerms = $terms;

        return $this;
    }

    /**
     * Get the terms to exclude in the suggestion list
     *
     * @return string[]
     */
    public function getExcludeTerms(): array
    {
        return $this->excludeTerms;
    }

    /**
     * Match the given search term against the users search
     *
     * @param string $term
     *
     * @return bool Whether the search matches or not
     */
    public function matchSearch(string $term): bool
    {
        if (! $this->searchPattern || $this->searchPattern === '.*') {
            return true;
        }

        return (bool) preg_match($this->searchPattern, $term);
    }

    /**
     * Load suggestions as requested by the client
     *
     * @param ServerRequestInterface $request
     *
     * @return $this
     */
    public function forRequest(ServerRequestInterface $request): self
    {
        if ($request->getMethod() !== 'POST') {
            return $this;
        }

        /** @var array<string, array<int|string, string>> $requestData */
        $requestData = json_decode($request->getBody()->read(8192), true);
        if (empty($requestData)) {
            return $this;
        }

        $this->setSearchTerm($requestData['term']['label']);
        $this->setOriginalSearchValue($requestData['term']['search']);
        $this->setExcludeTerms($requestData['exclude'] ?? []);

        return $this;
    }

    protected function assemble()
    {
        $groupingCallback = $this->getGroupingCallback();
        if ($groupingCallback) {
            $provider = yield_groups($this->provider, $groupingCallback);
        } else {
            $provider = [null => $this->provider];
        }

        /** @var iterable<?string, array<array<string, string>>> $provider */
        foreach ($provider as $group => $suggestions) {
            if ($group) {
                $this->addHtml(
                    new HtmlElement(
                        'li',
                        Attributes::create([
                            'class' => 'suggestion-title'
                        ]),
                        Text::create($group)
                    )
                );
            }

            foreach ($suggestions as $data) {
                $attributes = [
                    'type' => 'button',
                    'value' => $data['label'] ?? $data['search']
                ];
                foreach ($data as $name => $value) {
                    $attributes["data-$name"] = $value;
                }

                $this->addHtml(
                    new HtmlElement(
                        'li',
                        null,
                        new HtmlElement(
                            'input',
                            Attributes::create($attributes)
                        )
                    )
                );
            }
        }

        if ($this->isEmpty()) {
            $this->addHtml(new HtmlElement(
                'li',
                Attributes::create(['class' => 'nothing-to-suggest']),
                new HtmlElement('em', null, Text::create($this->translate('Nothing to suggest')))
            ));
        }
    }
}