-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicFormModelStruct.php
More file actions
472 lines (420 loc) · 15.6 KB
/
Copy pathDynamicFormModelStruct.php
File metadata and controls
472 lines (420 loc) · 15.6 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<?php
/**
* @author: Jens Giessmann <jg@handcode.de>
*
* @copyright: 2025, Jens Giessmann
*/
namespace handcode\dynamicFormModel;
use yii\base\DynamicModel;
use yii\base\InvalidConfigException;
use yii\helpers\Json;
/**
* this model can be used to validate a struct defined for a DynamicFromModel
* The struct must be provided as first constructor param as jsonString or array
*/
class DynamicFormModelStruct extends DynamicModel
{
/**
* should be false (default) if struct must be serializable as JSON
* as we can not "convert" closures in jsonString
*
* @var bool
*/
public $allowClosures = false;
/**
* if false (default) only "known" property options are allowed
*
* if true the validation only checks "known" property options
* and ignore all "unknown"
*
* @var bool
*/
public $allowUndefined = false;
/**
* dynamicFormModel class from which the constant values for option keys should be used.
* beside this is an edge case, it is required to be able to redefine key constant values
* in subclasses if required for whatever reason
*
* @var string
*/
public $dynamicFormModelClass = DynamicFormModel::class;
public function __construct(array|string $attributes = [], $config = [])
{
if (is_string($attributes)) {
try {
$encodedAttributes = Json::decode($attributes);
if ($encodedAttributes) {
$attributes = $encodedAttributes;
}
} catch (\Exception) {
\Yii::error('invalid json provided as struct', __METHOD__);
}
}
parent::__construct($attributes, $config);
}
public function rules()
{
if (!is_a($this->dynamicFormModelClass, DynamicFormModelInterface::class, true)) {
throw new InvalidConfigException('dynamicFormModel class must implement DynamicFormModelInterface');
}
$rules = parent::rules();
// as we are ian dynamic model context we must check if the (optional) attributes are set to prevent undefined errors
if ($this->hasAttribute($this->dynamicFormModelClass::KEY_PROPERTIES)) {
$rules[] = [[$this->dynamicFormModelClass::KEY_PROPERTIES], 'validateStructProperties'];
}
if ($this->hasAttribute($this->dynamicFormModelClass::KEY_INPUT)) {
$rules[] = [[$this->dynamicFormModelClass::KEY_INPUT], 'validateStructInput'];
}
if ($this->hasAttribute($this->dynamicFormModelClass::KEY_RULES)) {
$rules[] = [[$this->dynamicFormModelClass::KEY_RULES], 'validateStructRules'];
}
if ($this->hasAttribute($this->dynamicFormModelClass::KEY_NAME)) {
$rules[] = [[$this->dynamicFormModelClass::KEY_NAME], 'string'];
}
if ($this->hasAttribute($this->dynamicFormModelClass::KEY_FIELD_SET)) {
$rules[] = [[$this->dynamicFormModelClass::KEY_FIELD_SET], 'validateStructFieldset'];
}
return $rules;
}
/**
* validate root 'properties'
*
* @param $attribute
* @param $params
* @param $validator
*
* @return true|void
*/
public function validateStructProperties($attribute, $params, $validator)
{
$attributeValue = $this->{$attribute};
// if empty just return as anything here is optional
if (empty($attributeValue)) {
return true;
}
if (is_array($attributeValue)) {
foreach ($attributeValue as $key => $value) {
// if value is string, this is used as property name and must be a valid php var name
if (is_string($value) && $this->validateVarname($value, [$attribute, (string) $value])) {
continue;
}
// else: check the struct of the array and it's children
if (is_array($value)) {
// if we got an array, the key is the property name and therefor must be a valid php var name
$this->validateVarname($key, [$attribute, (string) $key]);
foreach ($value as $optionKey => $optionValue) {
// validate property type and if set to object the object values
if ($optionKey === $this->dynamicFormModelClass::KEY_PROPERTY_TYPE) {
$this->validatePropertyTypeValue($optionValue, [$attribute, $key, $optionKey]);
if ($optionValue === $this->dynamicFormModelClass::PROPERTY_TYPE_OBJECT) {
// here we MUST use the $value array from parent foreach and return (break)
// from this loop as object validation should validate all other
// option values itself.
$this->validatePropertyTypeObject($value, [$attribute, $key]);
break;
}
continue;
}
// validate property input values
if ($optionKey === $this->dynamicFormModelClass::KEY_INPUT) {
$this->validateInputValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// validate property rules values
if ($optionKey === $this->dynamicFormModelClass::KEY_RULES) {
$this->validateRulesValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// validate property fieldset value
if ($optionKey === $this->dynamicFormModelClass::KEY_FIELD_SET) {
$this->validateFieldsetValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// validate property hint value
if ($optionKey === $this->dynamicFormModelClass::KEY_HINT) {
$this->validatePropertyHintValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// validate property label value
if ($optionKey === $this->dynamicFormModelClass::KEY_LABEL) {
$this->validatePropertyLabelValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// validate property default value
if ($optionKey === $this->dynamicFormModelClass::KEY_VALUE) {
$this->validatePropertyDefaultValue($optionValue, [$attribute, $key, $optionKey]);
continue;
}
// strict validation here?
if (!$this->allowUndefined) {
$this->addError([$attribute, (string) $key], 'unknown option: ' . (string) $optionKey);
}
}
}
}
return;
}
$this->addError($attribute, 'type of ' . $attribute . ' must be: null or array');
}
/**
* validate root 'input'
*
* @param $attribute
* @param $params
* @param $validator
*/
public function validateStructInput($attribute, $params, $validator)
{
$this->validateInputValue($this->{$attribute}, $attribute);
}
/**
* validate root 'rules'
*
* @param $attribute
* @param $params
* @param $validator
*/
public function validateStructRules($attribute, $params, $validator)
{
$this->validateRulesValue($this->{$attribute}, $attribute);
}
/**
* validate root 'fieldset'
*
* @param $attribute
* @param $params
* @param $validator
*/
public function validateStructFieldset($attribute, $params, $validator)
{
$this->validateFieldsetValue($this->{$attribute}, $attribute);
}
/**
* validate root 'formName'
*
* @param $attribute
* @param $params
* @param $validator
*/
public function validateStructFormname($attribute, $params, $validator)
{
if (!$this->emptyOrString($this->{$attribute})) {
$this->addError($attribute, 'type of formName must be: null or string');
}
}
/**
* validate property type value
*
* @param $value
* @param $structPath
*/
protected function validatePropertyTypeValue($value, $structPath)
{
if (!is_string($value)) {
$this->addError($structPath, 'value for type must be a string');
}
if (!in_array($value, $this->dynamicFormModelClass::validPropertyTypes())) {
$this->addError($structPath, 'value for type is not a valid property type');
}
}
protected function validatePropertyTypeObject(array $struct, $structPath)
{
$validationModel = \Yii::createObject(static::class, [$struct]);
if (!$validationModel->validate()) {
if (is_array($validationModel->getErrors())) {
foreach ($validationModel->getErrors() as $path => $errors) {
$ePath = $structPath;
array_push($ePath, $path);
foreach ($errors as $error) {
$this->addError($ePath, $error);
}
}
} else {
$this->addError($structPath, 'undefined error while validating property of type object');
}
}
return empty($validationModel->getErrors());
}
/**
* validate value for one 'input' key
*
* @param $value
* @param array|string $structPath
*/
protected function validateInputValue($value, $structPath)
{
if ($this->emptyOrString($value)) {
return;
}
if (is_array($value)) {
foreach ($value as $optKey => $optValue) {
$optPath = self::pathAdd($optKey, $structPath);
// check callback options
if ($optKey === $this->dynamicFormModelClass::KEY_INPUT_CALLBACK
|| $optKey === $this->dynamicFormModelClass::KEY_INPUT_LIST_ITEMS_CALLBACK
) {
$this->validateCallbackValue($optValue, $optPath);
continue;
}
// check options that must be arrays
if ($optKey === $this->dynamicFormModelClass::KEY_INPUT_LIST_ITEM_VALUES
|| $optKey === $this->dynamicFormModelClass::KEY_INPUT_LIST_ITEMS
|| $optKey === $this->dynamicFormModelClass::KEY_INPUT_OPTIONS
) {
if (!is_array($optValue)) {
$this->addError($optPath, 'type of input.' . $optKey . ' must be an array');
}
continue;
}
// check string options
if ($optKey === $this->dynamicFormModelClass::KEY_INPUT_WIDGET) {
if (!$this->emptyOrString($optValue)) {
$this->addError($optPath, 'type of input.' . $optKey . ' must be: null or string');
}
}
}
return;
}
$this->addError($structPath, 'type of input must be: null, string or array');
}
/**
* validate value for one 'rules' key
*
* @param $value
* @param array|string $structPath
*/
public function validateRulesValue($value, $structPath)
{
if ($this->emptyOrString($value)) {
return;
}
if (is_array($value)) {
return;
}
$this->addError($structPath, 'type of rules must be: null, string or array');
}
/**
* validate the value for a fieldset key
*
* @param mixed $value
* @param array|string $structPath
*/
protected function validateFieldsetValue($value, $structPath)
{
if (!is_string($value)) {
$this->addError($structPath, 'value for fieldset must be a string');
}
}
/**
* validate the value for a property.label key
*
* @param mixed $value
* @param array|string $structPath
*/
protected function validatePropertyLabelValue($value, $structPath)
{
if (!$this->emptyOrString($value)) {
$this->addError($structPath, 'value for property.label must be null or string');
}
}
/**
* validate the value for a property.hint key
*
* @param mixed $value
* @param array|string $structPath
*/
protected function validatePropertyHintValue($value, $structPath)
{
if (!$this->emptyOrString($value)) {
$this->addError($structPath, 'value for property.hint must be null or string');
}
}
protected function validatePropertyDefaultValue($value, $structPath)
{
if (!is_scalar($value)) {
$this->addError($structPath, 'value for property.value must be scalar type');
}
}
/**
* validate if given value is a valid php var name
*
* @param mixed $value
* @param array|string $structPath
*
* @return bool
*/
protected function validateVarname($value, $structPath)
{
if (is_string($value) && preg_match('#^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$#', $value)) {
return true;
}
$this->addError($structPath, 'name must be valid php variable name');
return false;
}
protected function validateCallbackValue($value, $structPath)
{
// allow closures only if self::allowClosures == true
if (!$this->allowClosures && $value instanceof \Closure) {
$this->addError($structPath, 'closure callback values are not allowed in this struct');
}
// let's php itself check if the value can be used in call_user_func
// https://www.php.net/manual/de/function.is-callable.php
if (!is_callable($value)) {
$this->addError($structPath, 'callback value must be a callable');
}
}
/**
* check if value is empty or string
* can be used for simple empty || string checks
*
* @param $value
*
* @return bool
*/
protected function emptyOrString($value)
{
if (empty($value) || is_string($value)) {
return true;
}
return false;
}
/**
* @param array|string $attribute **overwrite parent**: if array we build a dot separated string from the given path values
* @param string $error
*/
public function addError($attribute, $error = '')
{
$errorKey = $this->buildErrorNameFromStructPath($attribute);
parent::addError($errorKey, $error);
}
/**
* generate string from given path array that is used as key for errors
*
* @param array|string $in
*
* @return string
*/
protected function buildErrorNameFromStructPath($in)
{
if (is_array($in)) {
return implode('.', $in);
}
return $in;
}
/**
* add $name to the end of the $path array
*
* @param $name
* @param $path
*
* @return mixed|string[]
*/
protected static function pathAdd($name, $path)
{
if (is_string($path)) {
$path = [$path];
}
$path[] = $name;
return $path;
}
}