Debian Codegraph @

vendor/ipl/web/src/Control/SortControl.php

raw
1 <?php
2
3 namespace ipl\Web\Control;
4
5 use GuzzleHttp\Psr7\ServerRequest;
6 use ipl\Html\Form;
7 use ipl\Html\FormDecorator\DivDecorator;
8 use ipl\Html\FormElement\ButtonElement;
9 use ipl\Html\HtmlElement;
10 use ipl\I18n\Translation;
11 use ipl\Orm\Common\SortUtil;
12 use ipl\Orm\Query;
13 use ipl\Stdlib\Str;
14 use ipl\Web\Common\FormUid;
15 use ipl\Web\Widget\Icon;
16 use Psr\Http\Message\ServerRequestInterface;
17
18 /**
19 * Allows to adjust the order of the items to display
20 */
21 class SortControl extends Form
22 {
23 use FormUid;
24 use Translation;
25
26 /** @var string Default sort param */
27 public const DEFAULT_SORT_PARAM = 'sort';
28
29 protected $defaultAttributes = ['class' => 'sort-control'];
30
31 /** @var string Name of the URL parameter which stores the sort column */
32 protected $sortParam = self::DEFAULT_SORT_PARAM;
33
34 /** @var array Possible sort columns as sort string-value pairs */
35 private $columns;
36
37 /** @var ?string Default sort string */
38 private $default;
39
40 protected $method = 'GET';
41
42 /**
43 * Create a new sort control
44 *
45 * @param array $columns Possible sort columns
46 *
47 * @internal Use {@see self::create()} instead.
48 */
49 private function __construct(array $columns)
50 {
51 $this->setColumns($columns);
52 }
53
54 /**
55 * Create a new sort control with the given options
56 *
57 * @param array<string,string> $options A sort spec to label map
58 *
59 * @return static
60 */
61 public static function create(array $options)
62 {
63 $normalized = [];
64 foreach ($options as $spec => $label) {
65 $normalized[SortUtil::normalizeSortSpec($spec)] = $label;
66 }
67
68 $self = new static($normalized);
69
70 $self->on(self::ON_REQUEST, function (ServerRequestInterface $request) use ($self) {
71 // If the form is submitted by POST, handleRequest() won't access the URL, so we have to
72 if (($sort = $request->getQueryParams()[$self->getSortParam()] ?? null)) {
73 $self->populate([$self->getSortParam() => $sort]);
74 }
75 });
76
77 return $self;
78 }
79
80 /**
81 * Get the possible sort columns
82 *
83 * @return array Sort string-value pairs
84 */
85 public function getColumns(): array
86 {
87 return $this->columns;
88 }
89
90 /**
91 * Set the possible sort columns
92 *
93 * @param array $columns Sort string-value pairs
94 *
95 * @return $this
96 */
97 public function setColumns(array $columns): self
98 {
99 // We're working with lowercase keys throughout the sort control
100 $this->columns = array_change_key_case($columns, CASE_LOWER);
101
102 return $this;
103 }
104
105 /**
106 * Get the default sort string
107 *
108 * @return ?string
109 */
110 public function getDefault(): ?string
111 {
112 return $this->default;
113 }
114
115 /**
116 * Set the default sort string
117 *
118 * @param string $default
119 *
120 * @return $this
121 */
122 public function setDefault(string $default): self
123 {
124 // We're working with lowercase keys throughout the sort control
125 $this->default = strtolower($default);
126
127 return $this;
128 }
129
130 /**
131 * Get the name of the URL parameter which stores the sort
132 *
133 * @return string
134 */
135 public function getSortParam(): string
136 {
137 return $this->sortParam;
138 }
139
140 /**
141 * Set the name of the URL parameter which stores the sort
142 *
143 * @param string $sortParam
144 *
145 * @return $this
146 */
147 public function setSortParam(string $sortParam): self
148 {
149 $this->sortParam = $sortParam;
150
151 return $this;
152 }
153
154 /**
155 * Get the sort string
156 *
157 * @return ?string
158 */
159 public function getSort(): ?string
160 {
161 $sort = $this->getPopulatedValue($this->getSortParam(), $this->getDefault());
162 if (! empty($sort)) {
163 $columns = $this->getColumns();
164
165 if (! isset($columns[$sort])) {
166 // Choose sort string based on the first closest match
167 foreach (array_keys($columns) as $key) {
168 if (Str::startsWith($key, $sort)) {
169 $this->populate([$this->getSortParam() => $key]);
170 $sort = $key;
171
172 break;
173 }
174 }
175 }
176 }
177
178 return $sort;
179 }
180
181 /**
182 * Sort the given query according to the request
183 *
184 * @param Query $query
185 * @param ?array|string $defaultSort
186 *
187 * @return $this
188 */
189 public function apply(Query $query, $defaultSort = null): self
190 {
191 $default = $defaultSort ?? (array) $query->getModel()->getDefaultSort();
192 if (! empty($default)) {
193 $this->setDefault(SortUtil::normalizeSortSpec($default));
194 }
195
196 $sort = $this->getSort();
197 if (! empty($sort)) {
198 $query->orderBy(SortUtil::createOrderBy($sort));
199 }
200
201 return $this;
202 }
203
204 /**
205 * Prepare the visual representation of the sort control
206 *
207 * This is called just before rendering happens. What is being done here, doesn't influence validity in any way.
208 * So there is no need to have the result already at hand during validation. Instead, delaying it allows
209 * to influence the visual result as long as possible.
210 *
211 * @return void
212 */
213 protected function prepareContent(): void
214 {
215 $columns = $this->getColumns();
216 $sort = $this->getSort();
217
218 if (empty($sort)) {
219 reset($columns);
220 $sort = key($columns);
221 }
222
223 $sort = explode(',', $sort, 2);
224 list($column, $direction) = Str::symmetricSplit(array_shift($sort), ' ', 2);
225
226 if (! $direction || strtolower($direction) === 'asc') {
227 $toggleIcon = 'sort-alpha-down';
228 $toggleDirection = 'desc';
229 } else {
230 $toggleIcon = 'sort-alpha-down-alt';
231 $toggleDirection = 'asc';
232 }
233
234 if ($direction !== null) {
235 $value = implode(',', array_merge(["{$column} {$direction}"], $sort));
236 if (! isset($columns[$value])) {
237 foreach ([$column, "{$column} {$toggleDirection}"] as $key) {
238 $key = implode(',', array_merge([$key], $sort));
239 if (isset($columns[$key])) {
240 $columns[$value] = $columns[$key];
241 unset($columns[$key]);
242
243 break;
244 }
245 }
246 }
247 } else {
248 $value = implode(',', array_merge([$column], $sort));
249 }
250
251 if (! isset($columns[$value])) {
252 $columns[$value] = 'Custom';
253 }
254
255 $this->addElement('select', $this->getSortParam(), [
256 'class' => 'autosubmit',
257 'label' => $this->translate('Sort By'),
258 'options' => $columns,
259 'value' => $value
260 ]);
261 $select = $this->getElement($this->getSortParam());
262 (new DivDecorator())->decorate($select);
263
264 // Apply Icinga Web 2 style, for now
265 $select->prependWrapper(HtmlElement::create('div', ['class' => 'icinga-controls']));
266
267 $toggleButton = new ButtonElement($this->getSortParam(), [
268 'class' => 'control-button spinner',
269 'title' => $this->translate('Change sort direction'),
270 'type' => 'submit',
271 'value' => implode(',', array_merge(["{$column} {$toggleDirection}"], $sort))
272 ]);
273 $toggleButton->add(new Icon($toggleIcon));
274
275 $this->addHtml($toggleButton);
276 }
277
278 protected function assemble()
279 {
280 if ($this->getMethod() === 'POST' && $this->hasAttribute('name')) {
281 $this->addElement($this->createUidElement());
282 }
283 }
284
285 public function renderUnwrapped()
286 {
287 $this->prepareContent();
288
289 return parent::renderUnwrapped();
290 }
291 }