PluginProbe
The Innovative Form Builder – IvyForms / 1.1.1
The Innovative Form Builder – IvyForms v1.1.1
1.5.1 1.5 1.4.1 1.4 trunk 0.1.2 0.2 0.2.1 0.3 0.3.1 0.4 0.5 0.6 0.6.1 0.6.1-backup 0.6.1.1 0.7 0.8 0.8.1 0.8.2 0.9 0.9.1 1.0 1.1 1.1.1 All 27 releases
ivyforms / backend / src / Factory / Field / FieldFactory.php

FieldFactory.php in The Innovative Form Builder – IvyForms 1.1.1, at backend/src/Factory/Field/FieldFactory.php

398 lines 16.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace IvyForms\Factory\Field;
4
5 use IvyForms\Common\Exceptions\ValidationException;
6 use IvyForms\Common\Helpers\NameFieldKeyHelper;
7 use IvyForms\Entity\Field\Field as FieldEntity;
8 use IvyForms\ValueObjects\Field\Field;
9 use IvyForms\ValueObjects\Field\FieldGeneralSettings;
10 use IvyForms\ValueObjects\Field\FieldOptions;
11 use IvyForms\ValueObjects\Field\FieldAdvancedSettings;
12 use IvyForms\ValueObjects\Field\ConfirmationGeneralSettings;
13 use IvyForms\ValueObjects\Field\TimeFieldGeneralSettings;
14 use IvyForms\ValueObjects\Field\DateFieldGeneralSettings;
15
16 /**
17 * Class FieldFactory
18 *
19 * @package IvyForms\Factory\Field
20 */
21 class FieldFactory
22 {
23 /**
24 * @param array<string, mixed> $data
25 *
26 * @return FieldEntity
27 *
28 * @throws ValidationException
29 */
30 public static function create(array $data): FieldEntity
31 {
32 $settings = self::parseSettings($data['settings'] ?? null);
33
34 if (!empty($settings)) {
35 $data['hideLabel'] = $settings['hideLabel'] ?? false;
36 $data['readOnly'] = $settings['readOnly'] ?? false;
37 $data['description'] = $settings['description'] ?? '';
38 $data['requiredMessage'] = $settings['requiredMessage'] ?? '';
39 $data['cssClasses'] = $settings['cssClasses'] ?? '';
40 $data['limitMaxLength'] = $settings['limitMaxLength'] ?? false;
41 $data['limitRange'] = $settings['limitRange'] ?? false;
42 $data['maxLength'] = $settings['maxLength'] ?? 255;
43 $data['labelPosition'] = $settings['labelPosition'] ?? 'default';
44 $data['noDuplicates'] = $settings['noDuplicates'] ?? false;
45 $data['shuffleOptions'] = $settings['shuffleOptions'] ?? false;
46 $data['showValues'] = $settings['showValues'] ?? false;
47 $data['enableSearch'] = $settings['enableSearch'] ?? false;
48 $data['rows'] = $settings['rows'] ?? 0;
49 $data['confirmFieldEnabled'] = $settings['confirmFieldEnabled'] ?? false;
50 $data['confirmFieldLabel'] = $settings['confirmFieldLabel'] ?? '';
51 $data['confirmFieldPlaceholder'] = $settings['confirmFieldPlaceholder'] ?? '';
52 $data['confirmFieldHideLabel'] = $settings['confirmFieldHideLabel'] ?? false;
53 $data['phoneFormat'] = $settings['phoneFormat'] ?? '';
54 $data['phoneAutoDetect'] = $settings['phoneAutoDetect'] ?? false;
55 $data['minValue'] = $settings['minValue'] ?? null;
56 $data['maxValue'] = $settings['maxValue'] ?? null;
57 $data['step'] = $settings['step'] ?? 1;
58 $data['showGrid'] = $settings['showGrid'] ?? false;
59 $data['numberFormat'] = $settings['numberFormat'] ?? '';
60 $data['inputPrefix'] = $settings['inputPrefix'] ?? '';
61 $data['inputSuffix'] = $settings['inputSuffix'] ?? '';
62 $data['timeFieldType'] = $settings['timeFieldType'] ?? '';
63 $data['timeFormat'] = $settings['timeFormat'] ?? '';
64 $data['minTimeValue'] = $settings['minTimeValue'] ?? '';
65 $data['maxTimeValue'] = $settings['maxTimeValue'] ?? '';
66 $data['dateFieldType'] = $settings['dateFieldType'] ?? '';
67 $data['dateFormat'] = $settings['dateFormat'] ?? '';
68 $data['minDateValue'] = $settings['minDateValue'] ?? '';
69 $data['maxDateValue'] = $settings['maxDateValue'] ?? '';
70 $data['showRatingText'] = $settings['showRatingText'] ?? false;
71 $data['ratingIcon'] = $settings['ratingIcon'] ?? 'star';
72 $data['htmlContent'] = $settings['htmlContent'] ?? '';
73 $data['agreementText'] = $settings['agreementText'] ?? '';
74 $data['limitDateRange'] = $settings['limitDateRange'] ?? false;
75 $data['limitTimeRange'] = $settings['limitTimeRange'] ?? false;
76 // Grid layout: prioritize direct database columns over settings JSON
77 // This ensures backward compatibility while preferring the dedicated columns
78 $data['rowIndex'] = $data['rowIndex'] ?? ($settings['rowIndex'] ?? 0);
79 $data['columnIndex'] = $data['columnIndex'] ?? ($settings['columnIndex'] ?? 0);
80 $data['width'] = $data['width'] ?? ($settings['width'] ?? 100);
81 $data['visible'] = array_key_exists('visible', $settings)
82 ? filter_var($settings['visible'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
83 : true;
84 if ($data['visible'] === null) {
85 $data['visible'] = true;
86 }
87 if (isset($settings['nameFieldType'])) {
88 $data['nameFieldType'] = (string)$settings['nameFieldType'];
89 }
90 if (array_key_exists('subFieldIndex', $settings)) {
91 $data['subFieldIndex'] = is_numeric($settings['subFieldIndex'])
92 ? (int)$settings['subFieldIndex']
93 : null;
94 }
95 }
96
97 if (isset($data['nameFieldType'])) {
98 $data['nameFieldType'] = (string)$data['nameFieldType'];
99 }
100 if (array_key_exists('subFieldIndex', $data)) {
101 $data['subFieldIndex'] = is_numeric($data['subFieldIndex'])
102 ? (int)$data['subFieldIndex']
103 : null;
104 }
105
106 if (empty($data['nameFieldType'])) {
107 $inferredNameFieldType = NameFieldKeyHelper::inferNameFieldKeyFromLabel($data['label'] ?? '');
108 if ($inferredNameFieldType !== null) {
109 $data['nameFieldType'] = $inferredNameFieldType;
110 }
111 }
112
113 /**
114 * Allows modification of the settings data before creating the Field entity.
115 * This filter runs for both:
116 * - Fields loaded from database (settings from JSON string)
117 * - Fields from API (settings from direct properties)
118 * @since 0.1.0
119 *
120 * @param mixed[] $data The current field data.
121 * @param mixed[] $settings The settings array (from database or empty for API).
122 * @return mixed[] The modified field data.
123 */
124 $data = apply_filters('ivyforms/field/factory/extract_settings', $data, $settings);
125 $generalSettings = new FieldGeneralSettings(
126 self::validateString($data['label'] ?? '', 255, 'label'),
127 self::validateBool($data['required'] ?? false),
128 self::validateString($data['placeholder'] ?? '', 255, 'placeholder'),
129 self::validateBool($data['hideLabel'] ?? false),
130 self::validateBool($data['readOnly'] ?? false),
131 self::validateString($data['description'] ?? '', 1000, 'description'),
132 self::validateString($data['requiredMessage'] ?? '', 255, 'requiredMessage'),
133 self::validateString($data['cssClasses'] ?? '', 255, 'cssClasses'),
134 self::validateBool($data['shuffleOptions'] ?? false),
135 self::validateBool($data['showValues'] ?? false),
136 self::validateBool($data['enableSearch'] ?? false),
137 self::validatePhoneFormat($data['phoneFormat'] ?? ''),
138 self::validateBool($data['phoneAutoDetect'] ?? false),
139 self::validateNumberValue($data['minValue'] ?? null, 'minValue'),
140 self::validateNumberValue($data['maxValue'] ?? null, 'maxValue'),
141 self::validateStep($data['step'] ?? 1),
142 self::validateBool($data['showGrid'] ?? false),
143 self::validateNumberFormat($data['numberFormat'] ?? ''),
144 new ConfirmationGeneralSettings(
145 self::validateBool($data['confirmFieldEnabled'] ?? false),
146 self::validateString(
147 $data['confirmFieldLabel'] ?? '',
148 255,
149 'confirmFieldLabel'
150 ),
151 self::validateString(
152 $data['confirmFieldPlaceholder'] ?? '',
153 255,
154 'confirmFieldPlaceholder'
155 ),
156 self::validateBool($data['confirmFieldHideLabel'] ?? false)
157 ),
158 new TimeFieldGeneralSettings(
159 self::validateBool($data['limitTimeRange'] ?? false),
160 self::validateString($data['timeFieldType'] ?? '', 50, 'timeFieldType'),
161 self::validateString($data['timeFormat'] ?? '', 50, 'timeFormat'),
162 isset($data['minTimeValue']) && $data['minTimeValue'] !== '' ?
163 self::validateString($data['minTimeValue'], 255, 'minTimeValue') : null,
164 isset($data['maxTimeValue']) && $data['maxTimeValue'] !== '' ?
165 self::validateString($data['maxTimeValue'], 255, 'maxTimeValue') : null,
166 ),
167 new DateFieldGeneralSettings(
168 self::validateBool($data['limitDateRange'] ?? false),
169 self::validateString($data['dateFieldType'] ?? '', 50, 'dateFieldType'),
170 self::validateString($data['dateFormat'] ?? '', 50, 'dateFormat'),
171 isset($data['minDateValue']) && $data['minDateValue'] !== '' ?
172 self::validateString($data['minDateValue'], 255, 'minDateValue') : null,
173 isset($data['maxDateValue']) && $data['maxDateValue'] !== '' ?
174 self::validateString($data['maxDateValue'], 255, 'maxDateValue') : null,
175 ),
176 self::validateBool($data['showRatingText'] ?? false),
177 self::validateBool($data['visible'] ?? true),
178 self::validateString($data['htmlContent'] ?? '', 4294967295, 'htmlContent'),
179 self::validateString($data['agreementText'] ?? '', 1000, 'agreementText'),
180 self::validateBool($data['limitRange'] ?? false),
181 );
182 $advancedSettings = new FieldAdvancedSettings(
183 self::validateString($data['defaultValue'] ?? '', 255, 'defaultValue'),
184 self::validateBool($data['limitMaxLength'] ?? false),
185 (int)($data['maxLength'] ?? 255),
186 self::validateString($data['labelPosition'] ?? '', 255, 'labelPosition'),
187 self::validateBool($data['noDuplicates'] ?? false),
188 self::validateString($data['inputPrefix'] ?? '', 255, 'inputPrefix'),
189 self::validateString($data['inputSuffix'] ?? '', 255, 'inputSuffix'),
190 self::validateString($data['ratingIcon'] ?? 'star', 50, 'ratingIcon')
191 );
192 $fieldOptions = new FieldOptions($data['options'] ?? []);
193
194 $fieldObject = new Field(
195 $data['id'] ?? 0,
196 $data['formId'] ?? 0,
197 $data['fieldIndex'] ?? 0,
198 $data['type'] ?? '',
199 $data['position'] ?? 0,
200 $generalSettings,
201 $fieldOptions,
202 $advancedSettings,
203 $data['parentId'] ?? null,
204 $data['rows'] ?? 0,
205 $data['rowIndex'] ?? 0,
206 $data['columnIndex'] ?? 0,
207 $data['width'] ?? 100,
208 $data['pageId'] ?? null
209 );
210
211 /**
212 * Allows setting of additional properties for the Field value object.
213 * @since 0.1.0
214 *
215 * @param Field $fieldObject The current field data.
216 * @param mixed[] $data The settings array from the database.
217 * @return mixed[] The modified field data.
218 */
219 $fieldObject = apply_filters('ivyforms/field/value_object/set_properties', $fieldObject, $data);
220
221 $field = new FieldEntity($fieldObject);
222
223 if (isset($data['id'])) {
224 $field->setId($data['id']);
225 }
226
227 if (isset($data['formId'])) {
228 $field->setFormId($data['formId']);
229 }
230
231 if (isset($data['fieldIndex'])) {
232 $field->setIndex($data['fieldIndex']);
233 }
234
235 if (isset($data['type'])) {
236 $field->setType($data['type']);
237 }
238
239 if (isset($data['position'])) {
240 $field->setPosition($data['position']);
241 }
242
243 if (isset($data['parentId'])) {
244 $field->setParentId($data['parentId']);
245 }
246
247 if (isset($data['pageId'])) {
248 $field->setPageId($data['pageId']);
249 }
250
251 if (isset($data['rows'])) {
252 $field->setRows((int)$data['rows']);
253 }
254
255 /**
256 * Allows setting of additional properties for the Field entity.
257 * @since 0.1.0
258 *
259 * @param FieldEntity $field The current field data.
260 * @param mixed[] $data The settings array from the database.
261 * @return mixed[] The modified field data.
262 */
263 $field = apply_filters('ivyforms/field/entity/set_properties', $field, $data);
264
265 if (!empty($data['nameFieldType'])) {
266 $field->setAdditionalProperty('nameFieldType', (string)$data['nameFieldType']);
267 }
268 if (array_key_exists('subFieldIndex', $data) && $data['subFieldIndex'] !== null) {
269 $field->setAdditionalProperty('subFieldIndex', (int)$data['subFieldIndex']);
270 }
271
272 return $field;
273 }
274
275 /**
276 * @param mixed $rawSettings
277 * @return array<string, mixed>
278 */
279 private static function parseSettings($rawSettings): array
280 {
281 if (is_array($rawSettings)) {
282 return $rawSettings;
283 }
284
285 if (!is_string($rawSettings) || $rawSettings === '') {
286 return [];
287 }
288
289 $decoded = json_decode($rawSettings, true);
290
291 return is_array($decoded) ? $decoded : [];
292 }
293
294 /**
295 * Validate and convert a value to boolean.
296 *
297 * @param mixed $value The value to validate.
298 *
299 * @return bool The validated boolean value.
300 */
301 private static function validateBool($value): bool
302 {
303 return (bool)$value;
304 }
305
306 /**
307 * Validate a string's length.
308 *
309 * @param mixed $value The value to validate.
310 * @param int $maxLength The maximum allowed length.
311 * @param string $fieldName The name of the field (for error messages).
312 *
313 * @return string The validated string.
314 *
315 * @throws ValidationException If the string exceeds the maximum length.
316 */
317 private static function validateString($value, int $maxLength, string $fieldName): string
318 {
319 $value = (string)$value;
320 if (strlen($value) > $maxLength) {
321 throw new ValidationException(
322 sprintf(
323 esc_html__('%1$s must be at most %2$d characters.', 'ivyforms'),
324 esc_html($fieldName),
325 $maxLength
326 )
327 );
328 }
329 return $value;
330 }
331 /**
332 * Validate and coerce numeric range values (minValue / maxValue).
333 * If value is null/empty/non-numeric => returns 0.0.
334 * Performs cross-check when the counterpart is already set.
335 *
336 * @param mixed $value
337 * @param string $fieldName 'minValue' | 'maxValue'
338 * @return float | null
339 * @throws ValidationException
340 */
341 private static function validateNumberValue($value, string $fieldName): ?float
342 {
343 if ($value === '' || $value === null) {
344 return null;
345 }
346 if (!is_numeric($value)) {
347 throw new ValidationException(
348 sprintf(
349 esc_html__('%1$s must be a number.', 'ivyforms'),
350 esc_html($fieldName)
351 )
352 );
353 }
354 return (float)$value;
355 }
356
357 /**
358 * Validate step (positive number >0)
359 * @param float $value
360 * @return float
361 * @throws ValidationException
362 */
363 private static function validateStep(float $value): float
364 {
365 if ($value <= 0) {
366 throw new ValidationException(esc_html__('step must be a positive number (>0).', 'ivyforms'));
367 }
368 return (float)$value;
369 }
370
371 /**
372 * Validates the number format.
373 *
374 * @param string $value
375 *
376 * @return string
377 *
378 */
379 private static function validateNumberFormat(string $value): string
380 {
381 $allowed = ['', 'us_decimal', 'us_int', 'eu_decimal', 'eu_int'];
382 if (!in_array($value, $allowed, true)) {
383 return '';
384 }
385 return $value;
386 }
387
388 private static function validatePhoneFormat(string $format): string
389 {
390 $allowed = ['international','national','e164'];
391 $lower = strtolower($format);
392 if (!in_array($lower, $allowed, true)) {
393 return 'international';
394 }
395 return $lower;
396 }
397 }
398