Debian Codegraph @

vendor/ipl/web/src/Common/FormUid.php

raw
1 <?php
2
3 namespace ipl\Web\Common;
4
5 use ipl\Html\Form;
6 use ipl\Html\Contract\FormElement;
7 use LogicException;
8
9 trait FormUid
10 {
11 protected $uidElementName = 'uid';
12
13 /**
14 * Create a form element to make this form distinguishable from others
15 *
16 * You'll have to define a name for the form for this to work.
17 *
18 * @return FormElement
19 */
20 protected function createUidElement()
21 {
22 /** @var Form $this */
23 $element = $this->createElement('hidden', $this->uidElementName, ['ignore' => true]);
24 $element->getAttributes()->registerAttributeCallback('value', function () {
25 /** @var Form $this */
26 return $this->getAttributes()->get('name')->getValue();
27 });
28
29 return $element;
30 }
31
32 /**
33 * Get whether the form has been sent
34 *
35 * A form is considered sent if the request's method equals the form's method
36 * and the sent UID is the form's UID.
37 *
38 * @return bool
39 */
40 public function hasBeenSent()
41 {
42 if (! parent::hasBeenSent()) {
43 return false;
44 } elseif ($this->getMethod() === 'GET') {
45 // Get forms are unlikely to require a UID. If they do, change this.
46 return true;
47 }
48
49 /** @var Form $this */
50 $name = $this->getAttributes()->get('name')->getValue();
51 if (! $name) {
52 throw new LogicException('Form has no name');
53 }
54
55 $values = $this->getRequest()->getParsedBody();
56
57 return isset($values[$this->uidElementName]) && $values[$this->uidElementName] === $name;
58 }
59 }