-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicFormModel.php
More file actions
970 lines (887 loc) · 32.8 KB
/
Copy pathDynamicFormModel.php
File metadata and controls
970 lines (887 loc) · 32.8 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
<?php
/**
* @author: Jens Giessmann <jg@handcode.de>
*
* @copyright: 2025, Jens Giessmann
*/
namespace handcode\dynamicFormModel;
use JsonSerializable;
use Yii;
use yii\base\DynamicModel;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\Json;
use yii\widgets\ActiveField;
use yii\widgets\ActiveForm;
/**
* DynamicFormModel implements an enhanced dynamicModel
* - that is configurable with a given config struct
* - that accepts attributes as json string as first param for _construct()
* - implements the JsonSerializable interface and therefor can be easily "used" as json
* - have a "funny" config struct that can be used to build very simple,
* but also very complex and flexible dynamicModels, with properties like hints, labels,...
* but also validation rules, inputFiled config and some more.
* - dynamicModels can have properties of type "object" which will be "self-contained"
* nested dynamicModels on their one.
*
* for more infos and examples, see ../README.md
*
* @property null|array|string $struct
* @property array $defaultRules
* @property array|mixed|string[] $defaultInput
*/
class DynamicFormModel extends DynamicModel implements \JsonSerializable, DynamicFormModelInterface
{
/**
* if true, and struct->properties is empty, the properties which are set via model constructor are used
*
* @var bool
*/
public $useConstructorAttributes = false;
/**
* set optional default fieldset name for all properties that have no fieldset defined
*/
public $defaultFieldSet;
/**
* class that is used in self::validateStruct() as validation model
*
* @var string
*/
public $structValidationModelClass = DynamicFormModelStruct::class;
/**
* class that should be used as object property validator to validate the
* child object(s).
* Must be of typ yii\validators\Validator
*
* @var string
*/
public $objectPropertyValidationClass = ObjectPropertyValidator::class;
/**
* id is a counter to store the number of instances of this class
* if no fromName is given via config struct,
* this counter will be appended to the parent::formName()
* to be able to init multiple instances in one form/request
* like id counter in widgets
*
* @var int
*/
protected static $id = 0;
/**
* false indicate that the struct is not set via self::setStruct() yet
*
* @var null|array|false|string
*/
protected $_struct;
/**
* stack with defined child objects
*
* @var DynamicFormModel[]
*/
protected $_objectProperties = [];
/**
* internal vars which are set while initialising the model from
* given struct
*
* @var array
*/
protected $_structPropertyNames = [];
protected $_defaultRules = [];
protected $_formName;
protected $_attributeHints = [];
protected $_propertyInputs = [];
protected $_defaultInput = [];
protected $_fieldSets = [];
protected $_hiddenFieldSet = '_';
protected $_structErrors;
/**
* overload the constructor of the base class so attributes can be provided as
* json string in addition to array as in parent
*
* {@inheritDoc}
*
* @param array|string $attributes
* @param $config
*/
public function __construct(array|string $attributes = [], $config = [])
{
if (static::jsonValidate($attributes)) {
$attributes = Json::decode($attributes) ?: [];
}
parent::__construct($attributes, $config);
}
/**
* just increment static counter used for dynamic formName default
*
* {@inheritDoc}
*/
public function init()
{
parent::init();
++self::$id;
}
/**
* if DynamicFormModel::KEY_NAME is defined in the struct this given value is returned,
* otherwise the value from parent::formName()
*
* @return string
*/
public function formName()
{
if (!empty($this->_formName)) {
return $this->_formName;
}
try {
$this->_formName = parent::formName() . self::$id;
} catch (InvalidConfigException $e) {
\Yii::warning('something went wrong while setting formName, fallback to basename of the called classFqdn');
$this->_formName = basename(str_replace('\\', '/', static::class)) . self::$id;
}
return $this->_formName;
}
/**
* we need a way to explicitly set the formName to control it independently of the struct
* (e.g. if one create multiple models from the same struct)
* and to ensure we have correct formNames for all child objects (properties with type = object)
* we must (re)set their formNames to, otherwise we have a race condition if the formName for this object is set
* AFTER initialising its struct
*
* @param $name
*/
public function setFormName($name)
{
$this->_formName = $name;
$this->setObjectPropertyFormNames();
}
/**
* (re)set the formName(s) for child objects in the internal objectProperties stack
*
* - if propertyName is given: formName is set only for the named object
* - else: formName is set for all existing objects in stack
*
* this method is called while initializing objectProperties
* AND each time self::setFormName() is called
*
* @see setFormName()
* @see initObjectProperty()
*
* @param null|string $propertyName
*
* @throws InvalidConfigException
*/
protected function setObjectPropertyFormNames($propertyName = null)
{
if (is_array($this->_objectProperties)) {
// just for one property object?
if (is_string($propertyName) && array_key_exists($propertyName, $this->_objectProperties)) {
$formName = $this->formName() . '[' . $propertyName . ']';
$this->_objectProperties[$propertyName]->setFormName($formName);
} else {
// else set formName for all defined objects
foreach ($this->_objectProperties as $name => $object) {
$formName = $this->formName() . '[' . $name . ']';
$object->setFormName($formName);
}
}
}
}
/**
* @param array|string $struct
*
* @return bool
*/
public function setStruct(array|string $struct)
{
try {
$this->_struct = $this->structToArray($struct);
} catch (\Exception) {
\Yii::error('invalid json provided as struct', __METHOD__);
return false;
}
return $this->initFromStruct();
}
/**
* return the defined struct for this model
*
* @return null|array|string
*/
public function getStruct()
{
return $this->_struct;
}
/**
* ensure we get an array from given struct
* - struct can be a php array -> nothing is done
* - a json string that can be decoded to the struct array
*
* @param array|string $struct
*
* @return null|array struct array or null if string is not valid json
*/
public function structToArray(array|string $struct)
{
if (is_array($struct)) {
return $struct;
}
if (is_string($struct)) {
try {
$encodedStruct = Json::decode($struct);
if ($encodedStruct) {
return $encodedStruct;
}
} catch (\Exception) {
\Yii::error('invalid json provided as struct', __METHOD__);
return null;
}
}
return null;
}
/**
* init the model according to the given struct
*
* @return false|void
*/
protected function initFromStruct()
{
if (!is_array($this->struct)) {
return false;
}
if (isset($this->struct[static::KEY_NAME])) {
$this->_formName = $this->struct[static::KEY_NAME];
}
if (isset($this->struct[static::KEY_RULES])) {
$this->initDefaultRules($this->struct[static::KEY_RULES]);
}
if (isset($this->struct[static::KEY_INPUT])) {
$this->initDefaultInput($this->struct[static::KEY_INPUT]);
}
if (!empty($this->struct[static::KEY_FIELD_SET]) && is_string($this->struct[static::KEY_FIELD_SET])) {
$this->defaultFieldSet = $this->struct[static::KEY_FIELD_SET];
}
if (isset($this->struct[static::KEY_PROPERTIES]) && is_array($this->struct[static::KEY_PROPERTIES])) {
$this->initProperties($this->struct[static::KEY_PROPERTIES]);
} else {
// should constructor attributes used as fallback?
if ($this->useConstructorAttributes && !empty($this->getAttributes())) {
$this->initProperties(array_keys($this->getAttributes()));
}
}
}
/**
* init the dynamicModel properties, input definitions and validation rules
*
* @param array $properties
*/
protected function initProperties(array $properties)
{
foreach ($properties as $name => $options) {
// if we only get a property name, init as options struct with defaults as we
// do not want to write redundant init code.
// in php the key name will be an int, but as in json the key can be also a string,
// so we only check $options here.
if (is_string($options)) {
$name = $options;
$options = [];
}
// if we have property name with options array
// we check and init the possible types and options
if (is_string($name) && is_array($options)) {
// fist ensure we have a valid type
$this->ensurePropertyType($name, $options);
switch ($options[static::KEY_PROPERTY_TYPE]) {
case static::PROPERTY_TYPE_OBJECT:
$this->initObjectProperty($name, $options);
break;
default:
$this->initAttributeProperty($name, $options);
break;
}
}
}
}
/**
* init property with type object
* - check that we have properties inside the object definition
* - inherit defined default rules and input options from this object
* if not defined in child object itself
* - init propertyName in this object scope
* - createObject with type static::class and $this->$name as constructor values,
* to init the attribute values within the new object
* - init the formName in the new object which is essential to be able to "identify"
* the child object values after form submit
* - add the new object to the internal objectProperties stack
*
* @param $name
* @param array $options
*
* @return false|void
*
* @throws InvalidConfigException
*/
protected function initObjectProperty($name, array $options)
{
if (!isset($options[static::KEY_PROPERTIES])) {
\Yii::error('type object must have properties', __CLASS__);
return false;
}
// init inherit defined root options from parent if not defined in child object itself
foreach ([static::KEY_RULES, static::KEY_INPUT] as $inheritKey) {
if (isset($this->struct[$inheritKey]) && !isset($options[$inheritKey])) {
$options[$inheritKey] = $this->struct[$inheritKey];
}
}
// init childModel with $this->$name values as constructor values
// to set the attribute => value pairs in child object
/** @var DynamicFormModelInterface $childModel */
$childValues = !empty($this->{$name}) ? $this->{$name} : [];
$childModel = \Yii::createObject(static::class, [$childValues]);
// be sure the options themselves are a valid struct
if ($childModel->validateStruct($options)) {
// if yes, init the options as struct in the childModel
$childModel->setStruct($options);
// add the childModel to the objectProperties stack
$this->_objectProperties[$name] = $childModel;
// and init formName of the object
$this->setObjectPropertyFormNames($name);
} else {
\Yii::error($childModel->getStructErrors());
unset($childModel);
return false;
}
// ensure property exists in this model
$this->ensureProperty($name, $childModel, true);
// add validation rule for the child
$this->addRule($name, $this->objectPropertyValidationClass);
}
/**
* init a "simple" scalar attribute property
*
* @param $name
* @param $options
*/
protected function initAttributeProperty($name, $options)
{
if (isset($options[static::KEY_VALUE])) {
$this->ensureProperty($name, $options[static::KEY_VALUE]);
} else {
$this->ensureProperty($name);
}
if (isset($options[static::KEY_RULES])) {
$this->ensurePropertyRules($name, $options[static::KEY_RULES]);
} else {
$this->ensurePropertyRules($name);
}
if (isset($options[static::KEY_INPUT])) {
$this->ensurePropertyInput($name, $options[static::KEY_INPUT]);
} else {
$this->ensurePropertyInput($name);
}
if (isset($options[static::KEY_FIELD_SET])) {
$this->addToFieldSet($name, $options[static::KEY_FIELD_SET]);
}
if (isset($options[static::KEY_LABEL])) {
$this->setAttributeLabel($name, $options[static::KEY_LABEL]);
}
if (isset($options[static::KEY_HINT])) {
$this->setAttributeHint($name, $options[static::KEY_HINT]);
}
}
/**
* @param $name
* @param $options array reference!
*/
protected function ensurePropertyType($name, array &$options)
{
if (!isset($options[static::KEY_PROPERTY_TYPE])) {
$options[static::KEY_PROPERTY_TYPE] = static::PROPERTY_TYPE_ATTRIBUTE;
return;
}
if (is_string($options[static::KEY_PROPERTY_TYPE])
&& in_array($options[static::KEY_PROPERTY_TYPE], static::validPropertyTypes())) {
return;
}
\Yii::error('invalid property type defined in struct for: ' . $name, __METHOD__);
}
/**
* return a list of valid property types
*
* @return string[]
*/
public static function validPropertyTypes()
{
return [
static::PROPERTY_TYPE_ATTRIBUTE,
static::PROPERTY_TYPE_OBJECT,
];
}
/**
* add property $name to the fieldSet $setName
*
* @param string $name
* @param $setName
*/
protected function addToFieldSet(string $name, $setName)
{
if (!array_key_exists($setName, $this->_fieldSets)) {
$this->_fieldSets[$setName] = [];
}
$this->_fieldSets[$setName][] = $name;
}
/**
* get the (optional) fieldset for given property name
*
* fieldset will be one of:
* - fieldset defined within property struct
* - defaultFieldSet of this model
* - _hiddenFieldSet defined in this model
*
* @param string $name
*
* @return string
*/
protected function getFieldSet(string $name)
{
if (!empty($this->_fieldSets)) {
foreach ($this->_fieldSets as $set => $properties) {
if (in_array($name, $properties)) {
return $set;
}
}
}
return $this->defaultFieldSet ?: $this->_hiddenFieldSet;
}
/**
* ensure we have a valid default input definition
*
* @param array|string $input
*/
protected function initDefaultInput(array|string $input)
{
if (is_array($input)) {
$this->_defaultInput = $input;
}
if (is_string($input)) {
$this->_defaultInput = [$input];
}
}
/**
* set the default Rules for this model that are used for all properties which have no own rule
* defined in static::struct
*
* - The given rules must be an array of rules or a string which can be decoded as Json
* - The resulting array should be an array of valid validation rules WITHOUT the first param (the property name)
* - The property name will be appended dynamically in the rule while initializing the properties from struct
*
* @param array|string $rules
*/
protected function initDefaultRules(array|string $rules)
{
if (is_array($rules)) {
$this->_defaultRules = $rules;
}
if (is_string($rules)) {
$this->_defaultRules = [$rules];
}
}
/**
* get the defaultInput config for each property that has no input defined in struct
*
* @return array
*/
public function getDefaultInput()
{
$fallback = [
'type' => 'text',
];
return $this->_defaultInput ?: $fallback;
}
/**
* get the defaultRule for each property that has no rule defined in struct
*
* @return array
*/
public function getDefaultRules()
{
$fallback = [
'trim',
['string', 'skipOnEmpty' => true],
];
return $this->_defaultRules ?: $fallback;
}
/**
* init the rules for given property from the rules values of the property struct itself,
* or as fallback from getDefaultRules()
*
* TODO: check and fix so that multiple calls results in "clean" rule set (no duplicates)
*
* @param string $name
* @param null|array|string $rules
*/
protected function ensurePropertyRules(string $name, mixed $rules = null)
{
$rules = $rules ?: $this->getDefaultRules();
// simply use rule as validator name, e.g. 'trim'
if (is_string($rules)) {
$this->addRule($name, $rules);
}
// if we get an array of rules, process them
if (is_array($rules)) {
foreach ($rules as $rule) {
// if this rule is just as string, use it as validator name
if (is_string($rule)) {
$this->addRule($name, $rule);
}
// if rule is an array, get the first element as validator name and use "the rest"
// as validator options
if (is_array($rule)) {
// get the first element from rule array as validator name
// the rest of rule array will be used as validator options
$validator = array_shift($rule);
if (!empty($validator)) {
$this->addRule($name, $validator, $rule ?: []);
}
}
}
}
}
/**
* init the input config for given property from the input values of the property struct itself,
* * or as fallback from getDefaultInput()
*
* @param string $name
* @param null|array|string $input
*/
protected function ensurePropertyInput(string $name, mixed $input = null)
{
$inputConfig = [
static::KEY_INPUT_CALLBACK => null,
static::KEY_INPUT_WIDGET => null,
static::KEY_INPUT_TYPE => null,
static::KEY_INPUT_OPTIONS => [],
static::KEY_INPUT_LIST_ITEMS => null,
static::KEY_INPUT_LIST_ITEMS_CALLBACK => null,
];
$input = $input ?: $this->getDefaultInput();
// if we get only one string as input config, just use it as input type.
if (is_string($input)) {
$inputConfig[static::KEY_INPUT_TYPE] = $input;
$this->_propertyInputs[$name] = $inputConfig;
return;
}
// if we got an array as input config we must check what should be done...
if (is_array($input)) {
// first, check if got subConfigs with known keys, if yes, assign them to the $inputConfig and
// remove them from given config.
// -> options as array?
if (array_key_exists(static::KEY_INPUT_OPTIONS, $input)
&& is_array($input[static::KEY_INPUT_OPTIONS])) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_OPTIONS, $input, $inputConfig);
}
// -> callback for the input?
if (array_key_exists(static::KEY_INPUT_CALLBACK, $input)
&& !empty($input[static::KEY_INPUT_CALLBACK])
&& is_callable($input[static::KEY_INPUT_CALLBACK])
) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_CALLBACK, $input, $inputConfig);
}
// -> widget class name as string?
if (array_key_exists(static::KEY_INPUT_WIDGET, $input)
&& is_string($input[static::KEY_INPUT_WIDGET])) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_WIDGET, $input, $inputConfig);
}
// -> no widget but type as string?
if (empty($inputConfig[static::KEY_INPUT_WIDGET])
&& array_key_exists(static::KEY_INPUT_TYPE, $input)
&& is_string($input[static::KEY_INPUT_TYPE])) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_TYPE, $input, $inputConfig);
}
// -> list itemsCallback as callable? if yes, assign and init items from callable
if (array_key_exists(static::KEY_INPUT_LIST_ITEMS_CALLBACK, $input)
&& !empty($input[static::KEY_INPUT_LIST_ITEMS_CALLBACK])
&& is_callable($input[static::KEY_INPUT_LIST_ITEMS_CALLBACK])) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_LIST_ITEMS_CALLBACK, $input, $inputConfig);
$inputConfig[static::KEY_INPUT_LIST_ITEMS] = call_user_func($inputConfig[static::KEY_INPUT_LIST_ITEMS_CALLBACK]);
}
// -> no list item callback but list items as an array?
if (empty($inputConfig[static::KEY_INPUT_LIST_ITEMS_CALLBACK])
&& array_key_exists(static::KEY_INPUT_LIST_ITEMS, $input)
&& is_array($input[static::KEY_INPUT_LIST_ITEMS])) {
$this->assignToAndUnsetFrom(static::KEY_INPUT_LIST_ITEMS, $input, $inputConfig);
}
// still no items but itemValues as an array that should be mapped as key->values?
if (empty($inputConfig[static::KEY_INPUT_LIST_ITEMS])
&& array_key_exists(static::KEY_INPUT_LIST_ITEM_VALUES, $input)
&& is_array($input[static::KEY_INPUT_LIST_ITEM_VALUES])) {
$inputConfig[static::KEY_INPUT_LIST_ITEMS] = array_combine($input[static::KEY_INPUT_LIST_ITEM_VALUES], $input[static::KEY_INPUT_LIST_ITEM_VALUES]);
$this->assignToAndUnsetFrom(static::KEY_INPUT_LIST_ITEM_VALUES, $input, $inputConfig);
}
// -> if still no callback, type or widget defined for this input, but we still have an "array"
// we use "the first array item as type", like yii do with className config in various places.
if (empty($inputConfig[static::KEY_INPUT_CALLBACK])
&& empty($inputConfig[static::KEY_INPUT_WIDGET])
&& empty($inputConfig[static::KEY_INPUT_TYPE])
&& is_array($input)) {
$inputConfig[static::KEY_INPUT_TYPE] = array_shift($input);
}
// -> if still no options for the input are defined, but we still have an "array"
// we use this array as options.
if (empty($inputConfig[static::KEY_INPUT_OPTIONS]) && is_array($input)) {
$inputConfig[static::KEY_INPUT_OPTIONS] = $input;
}
}
// Yii::debug($inputConfig);
$this->_propertyInputs[$name] = $inputConfig;
}
/**
* @param string $key
* @param array $from
* @param array $to
*/
private function assignToAndUnsetFrom(string $key, array &$from, array &$to)
{
$to[$key] = $from[$key];
unset($from[$key]);
}
/**
* ensure that the given $name exists as properties within this dynamicModel
* - if the property already exist, and $overwrite == false, nothing is done
* - if $overwrite == true, the value will be set
* - else, the property will be defined with given value
* - in all cases static::ensureStructProperty is called
*
* @param string $name
* @param null $value
* @param bool $overwrite
*/
protected function ensureProperty(string $name, $value = null, $overwrite = false)
{
if (!$this->hasAttribute($name) || $overwrite) {
$this->defineAttribute($name, $value);
}
$this->ensureStructProperty($name);
}
/**
* ensure the given property name is defined in _structPropertyNames which
* defines which values will be used in self::_toString and self::toJson()
*
* @param string $name
*/
protected function ensureStructProperty(string $name)
{
if (!in_array($name, $this->_structPropertyNames)) {
$this->_structPropertyNames[] = $name;
}
}
public function getAttributes($names = null, $except = [])
{
// if properties are set via self::setStruct() only the defined properties are used
if (!empty($this->_structPropertyNames) && !empty(parent::getAttributes())) {
return parent::getAttributes($this->_structPropertyNames);
}
return parent::getAttributes($names, $except);
}
/**
* return hints array merged from parent::attributeHints() and hint
* defined in dynamicModel struct
* Hint values can/will be set with self::setAttributeHint()
*
* @return array
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), $this->_attributeHints);
}
/**
* set hint for given attribute name
*
* @param string $name
* @param string $hint
*/
public function setAttributeHint(string $name, string $hint)
{
$this->_attributeHints[$name] = $hint;
}
/**
* return the ActiveForm fields for the properties defined
* in the struct of this model
*
* @param ActiveForm $form
*
* @return string
*
* @throws \Exception
*/
public function formFields(ActiveForm $form)
{
$inputs = [];
$properties = $this->getAttributes();
// init default fieldset
$fieldsets = [];
foreach ($properties as $property => $value) {
if (is_string($property)) {
// if property is an object itself, get formFields from the object and add them to a fieldset with the property name
if (array_key_exists($property, $this->_objectProperties)) {
$fieldsets[$property][] = $this->_objectProperties[$property]->formFields($form);
} else {
// else, get the input from the property
$set = $this->getFieldSet($property) ?: $this->_hiddenFieldSet;
$fieldsets[$set][] = $this->getActiveFieldForProperty($form, $property);
}
}
}
$out = [];
foreach ($fieldsets as $set => $inputs) {
// properties in hidden fieldset require no fieldSet Tag
if (!is_string($set) || $set === $this->_hiddenFieldSet) {
$out[] = implode(PHP_EOL, $inputs);
} else {
$out[] = Html::beginTag('fieldset');
$out[] = Html::tag('legend', Html::encode(Inflector::titleize($set)));
$out[] = implode(PHP_EOL, $inputs);
$out[] = Html::endTag('fieldset');
}
}
return implode(PHP_EOL, $out);
}
/**
* @param ActiveForm $form
* @param string $property
*
* @return ActiveField
*
* @throws \Exception
*/
protected function getActiveFieldForProperty(ActiveForm $form, string $property)
{
// get the ActiveField instance for this property in this form
$activeField = $form->field($this, $property);
// do we have input config for this property?
if (!empty($this->_propertyInputs[$property])) {
$inputConfig = $this->_propertyInputs[$property];
// callback which provide the whole form input?
if (!empty($inputConfig[static::KEY_INPUT_CALLBACK])) {
return call_user_func(
$inputConfig[static::KEY_INPUT_CALLBACK],
$form,
$this,
$property,
$inputConfig[static::KEY_INPUT_OPTIONS]
);
}
// should an inputWidget initialized?
if (!empty($inputConfig[static::KEY_INPUT_WIDGET])) {
return $activeField->widget(
$inputConfig[static::KEY_INPUT_WIDGET],
$inputConfig[static::KEY_INPUT_OPTIONS]
);
}
// check if we have a valid ActiveField methodName as type, if yes we will call this method
if (is_string($inputConfig[static::KEY_INPUT_TYPE]) && $activeField->hasMethod(
$inputConfig[static::KEY_INPUT_TYPE]
)) {
$inputMethodName = $inputConfig[static::KEY_INPUT_TYPE];
// if we get items, it "seems" that we should set items as first param as for dropDownList(), checkboxList(),....
if (!empty($inputConfig[static::KEY_INPUT_LIST_ITEMS])) {
return $activeField->{$inputMethodName}(
$inputConfig[static::KEY_INPUT_LIST_ITEMS],
$inputConfig[static::KEY_INPUT_OPTIONS]
);
}
// without items, just call the method with given options
return $activeField->{$inputMethodName}($inputConfig[static::KEY_INPUT_OPTIONS]);
}
// otherwise, initialize a "normal" ActiveField input with the given type as option.
return $activeField->input(
$inputConfig[static::KEY_INPUT_TYPE],
$inputConfig[static::KEY_INPUT_OPTIONS]
);
}
// still here? then this is the very last fallback for undefined property inputs...
return $activeField->input('text');
}
/**
* get object properties as json from Serializer
*
* @return string
*
* @throws \JsonException
*/
public function toJson()
{
return json_encode($this, JSON_THROW_ON_ERROR);
}
/**
* @throws \JsonException
*/
public function __toString()
{
return $this->toJson() ?: '';
}
/**
* get the properties defined in struct as array for jsonSerializer like e.g. json_encode
*
* implementation of the JsonSerializable interface
* {@inheritDoc}
*/
public function jsonSerialize(): mixed
{
$properties = $this->getAttributes();
ksort($properties);
return $properties ?: [];
}
/**
* @param $json
* @param $depth
* @param $flags
*
* @return bool
*/
protected static function jsonValidate($json, $depth = 512, $flags = 0)
{
if (!is_string($json)) {
return false;
}
// only available since php >= 8.3
if (function_exists('json_validate')) {
return json_validate($json);
}
// ... else fallback for php < 8.3
try {
json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR);
return true;
} catch (\JsonException $e) {
return false;
}
}
/**
* create a validation model of type self::structValidationModelClass with given struct
* if validation has errors, add these to this->structErrors
*
*
*
* @param null|array|string $struct
* @param bool $allowClosures
* @return bool
*
* @throws InvalidConfigException
*/
public function validateStruct(array|string|null $struct = null, bool $allowClosures = false)
{
$struct = $struct ?? $this->getStruct();
$validationModel = \Yii::createObject($this->structValidationModelClass, [$struct]);
$validationModel->dynamicFormModelClass = static::class;
$validationModel->allowClosures = $allowClosures;
if (!$validationModel->validate()) {
$this->_structErrors = $validationModel->getErrors();
}
unset($validationModel);
return empty($this->_structErrors);
}
/**
* @return null|array
*/
public function getStructErrors()
{
return $this->_structErrors;
}
}