-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAbstractJsonFormsForm.php
More file actions
243 lines (210 loc) · 8.26 KB
/
AbstractJsonFormsForm.php
File metadata and controls
243 lines (210 loc) · 8.26 KB
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
<?php
/*
* Copyright (C) 2022 SYSTOPIA GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Drupal\json_forms\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\json_forms\Form\Util\FieldNameUtil;
use Drupal\json_forms\Form\Util\FormCallbackExecutor;
use Drupal\json_forms\Form\Util\FormValidationUtil;
use Drupal\json_forms\Form\Validation\FormValidationMapperInterface;
use Drupal\json_forms\Form\Validation\FormValidatorInterface;
use Drupal\json_forms\JsonForms\Definition\DefinitionFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base class for JSON Forms.
*
* Subclasses should return the result of buildJsonFormsForm() in their
* implementation of buildForm().
*
* @phpstan-consistent-constructor
*
* Note: Properties must not be private, otherwise they get lost when form state
* is recovered from cache: https://www.drupal.org/project/drupal/issues/3097143
*
* @see self::buildJsonFormsForm()
*/
abstract class AbstractJsonFormsForm extends FormBase {
public const FLAG_RECALCULATE_ONCHANGE = 1;
public const INTERNAL_VALUES_KEY = '__';
protected FormArrayFactoryInterface $formArrayFactory;
protected FormValidatorInterface $formValidator;
protected FormValidationMapperInterface $formValidationMapper;
/**
* {@inheritDoc}
*
* @return static
*/
public static function create(ContainerInterface $container) {
return new static($container->get(FormArrayFactoryInterface::class),
$container->get(FormValidatorInterface::class), $container->get(FormValidationMapperInterface::class));
}
public function __construct(
FormArrayFactoryInterface $formArrayFactory,
FormValidatorInterface $formValidator,
FormValidationMapperInterface $formValidationMapper
) {
$this->formArrayFactory = $formArrayFactory;
$this->formValidator = $formValidator;
$this->formValidationMapper = $formValidationMapper;
}
/**
* Subclasses should call this method in their implementation of buildForm().
*
* To build a form with existing data, set the data as temporary in the form
* state until the form state is cached (but not later).
*
* @param array<int|string, mixed> $form
* @param \Drupal\Core\Form\FormStateInterface $formState
* @param \stdClass $jsonSchema
* @param \stdClass $uiSchema
*
* @return array<int|string, mixed>
* Should be used as return value of buildForms().
*
* @throws \InvalidArgumentException
*
* @see \Drupal\Core\Form\FormInterface::buildForm()
* @see FormStateInterface::setTemporary()
* @see FormStateInterface::isCached()
*/
protected function buildJsonFormsForm(
array $form,
FormStateInterface $formState,
\stdClass $jsonSchema,
\stdClass $uiSchema,
int $flags = 0
): array {
$recalculateOnChange = (bool) ($flags & self::FLAG_RECALCULATE_ONCHANGE);
$formState->set('jsonSchema', $jsonSchema);
$formState->set('uiSchema', $uiSchema);
$formState->set('recalculateOnChange', $recalculateOnChange);
// @phpstan-ignore equal.notAllowed
if (new \stdClass() == $uiSchema) {
return [];
}
if (property_exists($jsonSchema, '$limitValidation')) {
$formState->set('$limitValidationUsed', TRUE);
}
if ($formState->isRebuilding()) {
$formState->set('$hasCalcInitField', FALSE);
}
$definition = DefinitionFactory::createDefinition($uiSchema, $jsonSchema);
$form = $this->formArrayFactory->createFormArray($definition, $formState);
if (TRUE === $formState->get('$limitValidationUsed')) {
// Disable HTML form validation.
// @phpstan-ignore offsetAccess.nonOffsetAccessible
$form['#attributes']['novalidate'] = TRUE;
}
$form['#attributes']['class'][] = 'json-forms';
$form['#attached']['library'][] = 'json_forms/disable_buttons_on_ajax';
$form['#attached']['library'][] = 'json_forms/vertical_tabs';
if (!$formState->isCached() || $formState->isRebuilding()) {
if (TRUE === $formState->get('$calculateUsed')) {
$form['#attached']['library'][] = 'json_forms/initial_calculation';
}
// Drupal prevents caching on safe methods.
if (!$this->getRequest()->isMethodSafe()) {
$formState->setCached();
}
}
return $form;
}
/**
* @param array<int|string, mixed> $form
* @param \Drupal\Core\Form\FormStateInterface $formState
*/
public function validateForm(array &$form, FormStateInterface $formState): void {
parent::validateForm($form, $formState);
if ($formState->isSubmitted() || $formState->isValidationEnforced()) {
FormCallbackExecutor::executePreSchemaValidationCallbacks($formState);
if (TRUE === $formState->get('$limitValidationUsed')) {
// We cannot use Drupal validation errors if the form uses limited
// validation. They might contain errors that with the submitted data
// would be ignored. (Avoiding Drupal validation is not possible on form
// submit.)
$keepFormErrorElementKeys = FormValidationUtil::getKeepFormErrorElementKeys($formState);
$keepFormErrors = array_map(
fn (array $elementKey) => $formState->getError(['#parents' => $elementKey]),
$keepFormErrorElementKeys
);
$formState->clearErrors();
foreach ($keepFormErrorElementKeys as $index => $elementKey) {
if (NULL !== $keepFormErrors[$index]) {
$element = ['#parents' => $elementKey];
$formState->setError($element, $keepFormErrors[$index]);
}
}
}
$validationResult = $this->formValidator->validate(
// @phpstan-ignore-next-line
$formState->get('jsonSchema'),
$this->getSubmittedData($formState)
);
$this->formValidationMapper->mapErrors($validationResult, $formState);
$this->formValidationMapper->mapData($validationResult, $formState);
}
}
/**
* @phpstan-return array<int|string, mixed>
*/
public function calculateData(FormStateInterface $formState): array {
$validationResult = $this->formValidator->validate(
// @phpstan-ignore-next-line
$formState->get('jsonSchema'),
$this->getSubmittedData($formState)
);
return $validationResult->getData();
}
/**
* Subclasses may override doGetSubmittedData()
*
* @return array<int|string, mixed>
* The values of the form state with keys converted to JSON schema names and
* without Drupal internal values such as form_id. So the returned array
* should only contain keys described in the JSON schema.
*
* @see doGetSubmittedData()
*/
final protected function getSubmittedData(FormStateInterface $formState): array {
$key = '__submittedData';
if (!$formState->hasTemporaryValue($key)) {
$formState->setTemporaryValue($key, $this->doGetSubmittedData($formState));
}
// @phpstan-ignore-next-line
return $formState->getTemporaryValue($key);
}
/**
* @return array<int|string, mixed>
* The values of the form state with keys converted to JSON schema names and
* without Drupal internal values such as form_id. So the returned array
* should only contain keys described in the JSON schema.
*/
protected function doGetSubmittedData(FormStateInterface $formState): array {
// Remove internal values (e.g. add buttons for array elements)
$formState->unsetValue(self::INTERNAL_VALUES_KEY);
// We cannot use $formState->cleanValues() because it also drops the submit
// button value.
$data = array_filter(
$formState->getValues(),
fn ($key) => !in_array($key, $formState->getCleanValueKeys(), TRUE),
ARRAY_FILTER_USE_KEY
);
return FieldNameUtil::toJsonData($data);
}
}