Debian Codegraph @

vendor/ipl/web/src/Compat/CompatForm.php

raw
1 <?php
2
3 namespace ipl\Web\Compat;
4
5 use Icinga\Application\Icinga;
6 use Icinga\Application\Logger;
7 use Icinga\Exception\IcingaException;
8 use InvalidArgumentException;
9 use ipl\Html\Contract\FormElement;
10 use ipl\Html\Contract\FormSubmitElement;
11 use ipl\Html\Contract\HtmlElementInterface;
12 use ipl\Html\Form;
13 use ipl\Html\FormElement\SubmitButtonElement;
14 use ipl\Html\FormElement\SubmitElement;
15 use ipl\Html\HtmlDocument;
16 use ipl\Html\HtmlString;
17 use ipl\I18n\Translation;
18 use ipl\Web\Compat\FormDecorator\PrimaryButtonDecorator;
19 use ipl\Web\FormDecorator\IcingaFormDecorator;
20 use ipl\Web\Compat\FormDecorator\LabelDecorator;
21 use Stringable;
22 use Throwable;
23
24 class CompatForm extends Form
25 {
26 use Translation;
27
28 protected $defaultAttributes = ['class' => 'icinga-form icinga-controls'];
29
30 /** @var bool Whether to disable the legacy form decorator */
31 private bool $disableLegacyDecorator = false;
32
33 /**
34 * Apply default element decorators
35 *
36 * This method must be called before adding any elements to the form.
37 *
38 * Calling this method disables the legacy decorator.
39 *
40 * @return $this
41 */
42 public function applyDefaultElementDecorators(): static
43 {
44 $this->disableLegacyDecorator = true;
45
46 $this->addElementDecoratorLoaderPaths([
47 ['ipl\\Web\\Compat\\FormDecorator', 'Decorator']
48 ]);
49
50 $this->getDecorators()->addDecorators([
51 'PrimaryButton' => new PrimaryButtonDecorator(),
52 'Required' => [
53 'name' => LabelDecorator::class,
54 'options' => ['uniqueName' => fn(string $name) => Icinga::app()->getRequest()->protectId($name)]
55 ]
56 ]);
57
58 $this->setDefaultElementDecorators([
59 'Label' => $this->getDecorators()->getDecorator('Required'),
60 'LabelGroup' => [
61 'name' => 'HtmlTag',
62 'options' => [
63 'tag' => 'div',
64 'class' => 'control-label-group',
65 'condition' => function (FormElement $element): bool {
66 return ! $element instanceof FormSubmitElement
67 && (! $element instanceof HtmlElementInterface || $element->getTag() !== 'fieldset');
68 }
69 ]
70 ],
71 'Fieldset',
72 'Checkbox' => [
73 'name' => 'Checkbox',
74 'options' => [
75 'uniqueName' => fn(string $name) => Icinga::app()->getRequest()->protectId($name)
76 ]
77 ],
78 'RenderElement',
79 'AutosubmitIndication' => [
80 'name' => 'AutosubmitIndication',
81 'options' => [
82 'uniqueName' => fn(string $name) => Icinga::app()->getRequest()->protectId($name)
83 ]
84 ],
85 'Description' => [
86 'name' => 'Description',
87 'options' => [
88 'uniqueName' => fn(string $name) => Icinga::app()->getRequest()->protectId($name)
89 ]
90 ],
91 'Errors' => ['name' => 'Errors', 'options' => ['class' => 'errors']],
92 'ControlGroup' => [
93 'name' => 'HtmlTag',
94 'options' => [
95 'tag' => 'div',
96 'class' => 'control-group',
97 'condition' => fn(FormElement $element): bool => ! $element instanceof FormSubmitElement
98 ]
99 ],
100 'FormControls' => [
101 'name' => 'HtmlTag',
102 'options' => [
103 'tag' => 'div',
104 'class' => 'control-group form-controls',
105 'condition' => fn(FormElement $element): bool => $element instanceof FormSubmitElement
106 ]
107 ],
108 ]);
109
110 return $this;
111 }
112
113 /**
114 * Render the content of the element to HTML
115 *
116 * A duplicate of the primary submit button is being prepended if there is more than one present
117 *
118 * @return string
119 */
120 public function renderContent(): string
121 {
122 if (count($this->submitElements) > 1) {
123 return (new HtmlDocument())
124 ->setHtmlContent(
125 $this->duplicateSubmitButton($this->submitButton),
126 new HtmlString(parent::renderContent())
127 )
128 ->render();
129 }
130
131 return parent::renderContent();
132 }
133
134 public function hasDefaultElementDecorator()
135 {
136 if ($this->disableLegacyDecorator) {
137 return false;
138 }
139
140 if (parent::hasDefaultElementDecorator()) {
141 return true;
142 }
143
144 $this->setDefaultElementDecorator(new IcingaFormDecorator());
145
146 return true;
147 }
148
149 protected function ensureDefaultElementLoaderRegistered()
150 {
151 if (! $this->defaultElementLoaderRegistered) {
152 $this->addPluginLoader(
153 'element',
154 'ipl\\Web\\FormElement',
155 'Element'
156 );
157
158 parent::ensureDefaultElementLoaderRegistered();
159 }
160
161 return $this;
162 }
163
164 /**
165 * Return a duplicate of the given submit button with the `class` attribute fixed to `primary-submit-btn-duplicate`
166 *
167 * @param FormSubmitElement $originalSubmitButton
168 *
169 * @return FormSubmitElement
170 */
171 public function duplicateSubmitButton(FormSubmitElement $originalSubmitButton): FormSubmitElement
172 {
173 $attributes = (clone $originalSubmitButton->getAttributes())
174 ->set('class', 'primary-submit-btn-duplicate');
175 $attributes->remove('id');
176 // Remove to avoid `type="submit submit"` in SubmitButtonElement
177 $attributes->remove('type');
178
179 if ($originalSubmitButton instanceof SubmitElement) {
180 $newSubmitButton = new SubmitElement($originalSubmitButton->getName(), $attributes);
181 $newSubmitButton->setLabel($originalSubmitButton->getButtonLabel());
182
183 return $newSubmitButton;
184 } elseif ($originalSubmitButton instanceof SubmitButtonElement) {
185 $newSubmitButton = new SubmitButtonElement($originalSubmitButton->getName(), $attributes);
186 $newSubmitButton->setSubmitValue($originalSubmitButton->getSubmitValue());
187
188 return $newSubmitButton;
189 }
190
191 throw new InvalidArgumentException(sprintf(
192 'Cannot duplicate submit button of type "%s"',
193 get_class($originalSubmitButton)
194 ));
195 }
196
197 /**
198 * Log an error and surface it as a form message
199 *
200 * $template may contain a `{error}` placeholder, which is replaced with the error
201 * message. Any additional $args are forwarded to {@see Form::addMessage()} for
202 * further `sprintf()`-style formatting of $template:
203 *
204 * $this->logAndShowError($e, $this->translate('Method "%s" failed: {error}'), $name);
205 *
206 * @param Throwable|string $error Exception or error message to log and display
207 * @param string $template Message to show in the form. {error} is replaced with the
208 * error message.
209 * @param mixed ...$args Additional arguments for $template
210 *
211 * @return void
212 */
213 protected function logAndShowError(Throwable|string $error, string $template, mixed ...$args): void
214 {
215 if ($error instanceof Throwable) {
216 Logger::error("%s\n%s", $error->getMessage(), IcingaException::getConfidentialTraceAsString($error));
217 $errorMessage = $error->getMessage();
218 } else {
219 Logger::error($error);
220 $errorMessage = $error;
221 }
222
223 $this->addMessage(str_replace('{error}', $errorMessage, $template), ...$args);
224 $this->onError();
225 }
226 }