Debian Codegraph @

vendor/ipl/html/src/Form.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use Generator;
6 use ipl\Html\Contract\DefaultFormElementDecoration;
7 use ipl\Html\Contract\FormDecoration;
8 use ipl\Html\Contract\FormElement;
9 use ipl\Html\Contract\FormSubmitElement;
10 use ipl\Html\FormDecoration\DecoratorChain;
11 use ipl\Html\FormDecoration\FormDecorationResult;
12 use ipl\Html\FormElement\FormElements;
13 use ipl\Stdlib\Messages;
14 use Psr\Http\Message\ServerRequestInterface;
15 use Throwable;
16
17 class Form extends BaseHtmlElement implements Contract\Form, Contract\FormElements, DefaultFormElementDecoration
18 {
19 use FormElements {
20 FormElements::remove as private baseRemove;
21 FormElements::beforeRender as private baseBeforeRender;
22 }
23 use Messages;
24
25 /** @deprecated Use {@see Contract\Form::ON_SUBMIT} instead */
26 public const ON_SUCCESS = 'success';
27
28 /** @var string Form submission URL */
29 protected $action;
30
31 /** @var string HTTP method to submit the form with */
32 protected $method = 'POST';
33
34 /** @var FormSubmitElement Primary submit button */
35 protected $submitButton;
36
37 /** @var FormSubmitElement[] Other elements that may submit the form */
38 protected $submitElements = [];
39
40 /** @var bool Whether the form is valid */
41 protected $isValid;
42
43 /** @var ServerRequestInterface The server request being processed */
44 protected $request;
45
46 /** @var string */
47 protected $redirectUrl;
48
49 /** @var ?DecoratorChain<FormDecoration> */
50 protected ?DecoratorChain $decorators = null;
51
52 /** @var bool Whether the form has been decorated */
53 protected bool $decorated = false;
54
55 protected $tag = 'form';
56
57 /**
58 * Get whether the given value is empty
59 *
60 * @param mixed $value
61 *
62 * @return bool
63 */
64 public static function isEmptyValue($value): bool
65 {
66 return $value === null || $value === [] || (is_string($value) && trim($value) === '');
67 }
68
69 /**
70 * Return the given string unchanged.
71 *
72 * @param string $string
73 * @param bool $escapeBrackets
74 *
75 * @return string
76 * @deprecated Escaping element names must be explicitly done. This method does not escape
77 * anymore and will be removed in a future version.
78 */
79 public static function escapeReservedChars(string $string, bool $escapeBrackets = true): string
80 {
81 trigger_error(sprintf(
82 '%s is deprecated. Escaping element names must be explicitly done.',
83 __METHOD__
84 ), E_USER_DEPRECATED);
85
86 return $string;
87 }
88
89 public function getAction()
90 {
91 return $this->action;
92 }
93
94 /**
95 * Set the Form submission URL
96 *
97 * @param string $action
98 *
99 * @return $this
100 */
101 public function setAction($action)
102 {
103 $this->action = $action;
104
105 return $this;
106 }
107
108 public function getMethod()
109 {
110 return $this->method;
111 }
112
113 /**
114 * Set the HTTP method to submit the form with
115 *
116 * @param string $method
117 *
118 * @return $this
119 */
120 public function setMethod($method)
121 {
122 $this->method = strtoupper($method);
123
124 return $this;
125 }
126
127 /**
128 * Get whether the form has a primary submit button
129 *
130 * @return bool
131 */
132 public function hasSubmitButton()
133 {
134 return $this->submitButton !== null;
135 }
136
137 /**
138 * Get the primary submit button
139 *
140 * @return FormSubmitElement|null
141 */
142 public function getSubmitButton()
143 {
144 return $this->submitButton;
145 }
146
147 /**
148 * Set the primary submit button
149 *
150 * @param FormSubmitElement $element
151 *
152 * @return $this
153 */
154 public function setSubmitButton(FormSubmitElement $element)
155 {
156 $this->submitButton = $element;
157
158 return $this;
159 }
160
161 /**
162 * Get the submit element used to send the form
163 *
164 * @return FormSubmitElement|null
165 */
166 public function getPressedSubmitElement()
167 {
168 foreach ($this->submitElements as $submitElement) {
169 if ($submitElement->hasBeenPressed()) {
170 return $submitElement;
171 }
172 }
173
174 return null;
175 }
176
177 public function getRequest()
178 {
179 return $this->request;
180 }
181
182 public function setRequest($request)
183 {
184 $this->request = $request;
185
186 return $this;
187 }
188
189 /**
190 * Get the url to redirect to on success
191 *
192 * @return string
193 */
194 public function getRedirectUrl()
195 {
196 return $this->redirectUrl;
197 }
198
199 /**
200 * Set the url to redirect to on success
201 *
202 * @param string $url
203 *
204 * @return $this
205 */
206 public function setRedirectUrl($url)
207 {
208 $this->redirectUrl = $url;
209
210 return $this;
211 }
212
213 /**
214 * Get the decorators of this form
215 *
216 * @return DecoratorChain<FormDecoration>
217 */
218 public function getDecorators(): DecoratorChain
219 {
220 if ($this->decorators === null) {
221 $this->decorators = new DecoratorChain(FormDecoration::class);
222 }
223
224 return $this->decorators;
225 }
226
227 public function handleRequest(ServerRequestInterface $request)
228 {
229 $this->setRequest($request);
230
231 if (! $this->hasBeenSent()) {
232 $this->emit(Contract\Form::ON_REQUEST, [$request, $this]);
233
234 // Always assemble
235 $this->ensureAssembled();
236
237 return $this;
238 }
239
240 switch ($request->getMethod()) {
241 case 'POST':
242 $params = $request->getParsedBody();
243
244 break;
245 case 'GET':
246 parse_str($request->getUri()->getQuery(), $params);
247
248 break;
249 default:
250 $params = [];
251 }
252
253 $params = array_merge_recursive($params, $request->getUploadedFiles());
254 $this->populate($params);
255
256 // Assemble after populate in order to conditionally provide form elements
257 $this->ensureAssembled();
258
259 if ($this->hasBeenSubmitted()) {
260 if ($this->isValid()) {
261 try {
262 $this->emit(Contract\Form::ON_SENT, [$this]);
263 $this->onSuccess();
264 $this->emitOnce(Contract\Form::ON_SUBMIT, [$this]);
265 } catch (Throwable $e) {
266 $this->addMessage($e->getMessage());
267 $this->onError();
268 $this->emit(Contract\Form::ON_ERROR, [$e, $this]);
269 }
270 } else {
271 $this->onError();
272 }
273 } else {
274 $this->validatePartial();
275 $this->emit(Contract\Form::ON_SENT, [$this]);
276 }
277
278 return $this;
279 }
280
281 public function hasBeenSent()
282 {
283 if ($this->request === null) {
284 return false;
285 }
286
287 return $this->request->getMethod() === $this->getMethod();
288 }
289
290 public function hasBeenSubmitted()
291 {
292 if (! $this->hasBeenSent()) {
293 return false;
294 }
295
296 if ($this->hasSubmitButton()) {
297 return $this->getSubmitButton()->hasBeenPressed();
298 }
299
300 return true;
301 }
302
303 public function isValid()
304 {
305 if ($this->isValid === null) {
306 $this->validate();
307
308 $this->emit(Contract\Form::ON_VALIDATE, [$this]);
309 }
310
311 return $this->isValid;
312 }
313
314 /**
315 * Validate all elements
316 *
317 * @return $this
318 */
319 public function validate()
320 {
321 $this->ensureAssembled();
322
323 $valid = true;
324 foreach ($this->getElements() as $element) {
325 $element->validate();
326 if (! $element->isValid()) {
327 $valid = false;
328 }
329 }
330
331 $this->isValid = $valid;
332
333 return $this;
334 }
335
336 /**
337 * Validate all elements that have a value
338 *
339 * @return $this
340 */
341 public function validatePartial()
342 {
343 foreach ($this->yieldElementsRecursive($this) as $element) {
344 if ($element->hasValue()) {
345 $element->validate();
346 }
347 }
348
349 return $this;
350 }
351
352 public function remove(ValidHtml $content)
353 {
354 if ($this->submitButton === $content) {
355 $this->submitButton = null;
356 }
357
358 $this->baseRemove($content);
359
360 return $this;
361 }
362
363 /**
364 * Apply the form decoration
365 *
366 * @return void
367 */
368 protected function applyDecoration(): void
369 {
370 if ($this->decorated) {
371 return;
372 }
373
374 $result = new FormDecorationResult($this);
375 foreach ($this->getDecorators() as $decorator) {
376 $decorator->decorateForm($result, $this);
377 }
378
379 $this->decorated = true;
380 }
381
382 protected function onError()
383 {
384 $errors = Html::tag('ul', ['class' => 'errors']);
385 foreach ($this->getMessages() as $message) {
386 if ($message instanceof Throwable) {
387 $message = $message->getMessage();
388 }
389
390 $errors->addHtml(Html::tag('li', $message));
391 }
392
393 if (! $errors->isEmpty()) {
394 $this->prependHtml($errors);
395 }
396 }
397
398 protected function onSuccess()
399 {
400 // $this->redirectOnSuccess();
401 }
402
403 protected function onElementRegistered(FormElement $element)
404 {
405 if ($element instanceof FormSubmitElement) {
406 $this->submitElements[$element->getName()] = $element;
407
408 if (! $this->hasSubmitButton()) {
409 $this->setSubmitButton($element);
410 }
411 }
412
413 $element->onRegistered($this);
414 }
415
416 protected function registerAttributeCallbacks(Attributes $attributes)
417 {
418 $attributes
419 ->registerAttributeCallback('action', [$this, 'getAction'], [$this, 'setAction'])
420 ->registerAttributeCallback('method', [$this, 'getMethod'], [$this, 'setMethod']);
421 }
422
423 protected function beforeRender(): void
424 {
425 $this->baseBeforeRender();
426
427 $this->applyDecoration();
428 }
429
430 /**
431 * Yield all sub form elements of $from by traversing the form elements tree recursively
432 *
433 * Recurses into nested {@see FormElements} instances instead of yielding them directly.
434 *
435 * @param Contract\FormElements $from Entry point for traversing
436 *
437 * @return Generator<FormElement>
438 */
439 protected function yieldElementsRecursive(Contract\FormElements $from): Generator
440 {
441 if ($from instanceof HtmlDocument) {
442 $from->ensureAssembled();
443 }
444
445 foreach ($from->getElements() as $element) {
446 if ($element instanceof Contract\FormElements) {
447 yield from $this->yieldElementsRecursive($element);
448 } else {
449 yield $element;
450 }
451 }
452 }
453 }