-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScaffoldComponent.php
749 lines (631 loc) · 24.7 KB
/
ScaffoldComponent.php
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
<?php
namespace ride\web\orm\form;
use ride\library\decorator\EntryFormatDecorator;
use ride\library\form\component\AbstractComponent;
use ride\library\form\FormBuilder;
use ride\library\i18n\translator\Translator;
use ride\library\log\Log;
use ride\library\orm\definition\field\PropertyField;
use ride\library\orm\definition\field\BelongsToField;
use ride\library\orm\definition\field\HasManyField;
use ride\library\orm\definition\field\ModelField;
use ride\library\orm\definition\field\RelationField;
use ride\library\orm\definition\ModelTable;
use ride\library\orm\model\Model;
use ride\library\reflection\Boolean;
use ride\library\reflection\ReflectionHelper;
use ride\library\security\SecurityManager;
use ride\library\validation\validator\SizeValidator;
use ride\service\OrmService;
use ride\web\base\form\DateTimeComponent;
use ride\web\orm\taxonomy\OrmTagHandler;
use ride\web\WebApplication;
/**
* Form to edit ORM data
*/
class ScaffoldComponent extends AbstractComponent {
/**
* Instance of the web application
* @var \ride\web\WebApplication
*/
protected $web;
/**
* Instance of the reflection helper
* @var \ride\library\reflection\ReflectionHelper
*/
protected $reflectionHelper;
/**
* Instance of the security manager
* @var \ride\library\security\SecurityManager
*/
protected $securityManager;
/**
* Model of this form component
* @var \ride\library\orm\model\Model
*/
protected $model;
/**
* Locale for the fetched data
* @var string
*/
protected $locale;
/**
* Instance of the log
* @var \ride\library\log\Log
*/
protected $log;
/**
* Default field relation depth
* @var string
*/
protected $depth;
/**
* Names of the fields with their depth
* @var array
*/
protected $fieldDepths;
/**
* Names of the fields to hide
* @var array
*/
protected $hiddenFields;
/**
* Names of the fields to omit
* @var array
*/
protected $omittedFields;
/**
* Instance of the entry
* @var mixed
*/
protected $entry;
/**
* Array with the tabs
* @var array
*/
protected $tabs;
/**
* Constructs a new scaffold form component
* @param \ride\web\WebApplication $web Instance of the web application
* @param \ride\library\reflection\ReflectionHelper $reflectionHelper
* @param \ride\library\orm\model\Model $model
* @return null
*/
public function __construct(WebApplication $web, SecurityManager $securityManager, OrmService $ormService, Model $model) {
$this->web = $web;
$this->reflectionHelper = $model->getReflectionHelper();
$this->securityManager = $securityManager;
$this->ormService = $ormService;
$this->model = $model;
$this->locale = null;
$this->depth = 1;
$this->hiddenFields = array(
ModelTable::PRIMARY_KEY => true,
);
$this->omittedFields = array();
$this->fieldDepths = array();
$this->tabs = array();
$this->proxy = array();
$meta = $this->model->getMeta();
$tabs = $meta->getOption('scaffold.form.tabs');
if ($tabs) {
$tabs = explode(',', $tabs);
foreach ($tabs as $tab) {
$this->tabs[$tab] = array(
'translation' => $meta->getOption('scaffold.form.tab.' . $tab, 'label.' . $tab),
'rows' => array(),
);
}
}
$fields = $meta->getFields();
foreach ($fields as $fieldName => $field) {
if ($field->getOption('scaffold.form.omit')) {
$this->omittedFields[$fieldName] = true;
}
if ($field->getOption('scaffold.form.type') == 'hidden') {
$this->hiddenFields[$fieldName] = true;
}
$depth = $field->getOption('scaffold.form.depth');
if ($depth !== null) {
$this->fieldDepths[$fieldName] = $depth;
}
$permission = $field->getOption('scaffold.form.permission');
if ($permission && !$this->securityManager->isPermissionGranted($permission)) {
$this->omittedFields[$fieldName] = true;
}
if (isset($this->omittedFields[$fieldName]) || isset($this->hiddenFields[$fieldName])) {
continue;
}
$tab = $field->getOption('scaffold.form.tab');
if (isset($this->tabs[$tab])) {
$this->tabs[$tab]['rows'][$fieldName] = $fieldName;
}
}
}
/**
* Sets the instance of the log
* @param \ride\library\log\Log $log Instance of the log
* @return null
*/
public function setLog(Log $log) {
$this->log = $log;
}
/**
* Sets the default field depth for relation fields
* @param integer $depth
* @return null
*/
public function setDepth($depth) {
$this->depth = $depth;
}
/**
* Sets the depth for a relation field
* @param string $name Name of the field
* @param integer $depth Depth of the field
* @return null
*/
public function setFieldDepth($name, $depth) {
$this->fieldDepths[$name] = $depth;
}
/**
* Sets the locale for the fetched data
* @param string $locale
* @return null
*/
public function setLocale($locale) {
$this->locale = $locale;
}
/**
* Adds a field to the hidden fields
* @param string $name Name of the field
* @return null
*/
public function hideField($name) {
$this->hiddenFields[$name] = true;
}
/**
* Adds a field to the omitted fields
* @param string $name Name of the field
* @return null
*/
public function omitField($name) {
$this->omittedFields[$name] = true;
}
/**
* Gets the name of this component, used when this component is the root
* of the form to be build
* @return string
*/
public function getName() {
return 'form-' . strtolower($this->model->getName());
}
/**
* Gets the data type for the data of this form component
* @return string|null A string for a data class, null for an array
*/
public function getDataType() {
return $this->model->getMeta()->getEntryClassName();
}
/**
* Gets the tabs for this component
* @return array Array with the machine name of the tab as key and an array
* with the translation and rows elements
*/
public function getTabs() {
return $this->tabs;
}
/**
* Gets the added row names
* @return array Array with the field name as key and value
*/
public function getRowNames() {
$fields = $this->model->getMeta()->getFields();
foreach ($fields as $fieldName => $field) {
if (isset($this->omittedFields[$fieldName])) {
unset($fields[$fieldName]);
} else {
$fields[$fieldName] = $fieldName;
}
}
return $fields;
}
/**
* Parse the entry to form values for the component rows
* @param mixed $data
* @return array $data
*/
public function parseSetData($entry) {
if (!$entry) {
return null;
}
$this->entry = $entry;
$result = array();
$fields = $this->model->getMeta()->getFields();
foreach ($fields as $fieldName => $field) {
if (isset($this->omittedFields[$fieldName])) {
continue;
}
$value = $this->reflectionHelper->getProperty($entry, $fieldName);
if (isset($this->proxy[$fieldName])) {
if (is_array($value)) {
foreach ($value as $index => $indexValue) {
$value[$index] = $indexValue->getId();
}
} elseif ($value) {
$value = $value->getId();
}
}
$result[$fieldName] = $value;
}
return $result;
}
/**
* Parse the form values of an entry of this component
* @param array $data
* @return mixed Entry
*/
public function parseGetData(array $data) {
if (!$this->entry) {
$this->entry = $this->model->createEntry();
}
$meta = $this->model->getMeta();
if ($this->locale && $meta->isLocalized()) {
$this->entry->setLocale($this->locale);
}
$fields = $meta->getFields();
foreach ($fields as $fieldName => $field) {
if (isset($this->omittedFields[$fieldName])) {
continue;
}
if (isset($data[$fieldName])) {
$value = $data[$fieldName];
} else {
$value = null;
if ($field instanceof HasManyField) {
$value = array();
} elseif (!$field instanceof RelationField && $field->getType() == 'boolean') {
$value = false;
}
}
if (isset($this->proxy[$fieldName])) {
$relationModel = $this->model->getRelationModel($fieldName);
if (is_array($value)) {
foreach ($value as $index => $indexValue) {
$value[$index] = $relationModel->createProxy($indexValue, $this->locale);
}
} elseif ($value) {
$value = $relationModel->createProxy($value, $this->locale);
} else {
$value = null;
}
}
$this->reflectionHelper->setProperty($this->entry, $fieldName, $value);
}
return $this->entry;
}
/**
* Prepares the form builder by adding row definitions
* @param \ride\library\form\FormBuilder $builder
* @param array $options Extra options from the controller
* @return null
*/
public function prepareForm(FormBuilder $builder, array $options) {
$meta = $this->model->getMeta();
$validationConstraint = $this->model->getValidationConstraint();
if ($validationConstraint) {
$validationConstraintClass = get_class($validationConstraint);
switch ($validationConstraintClass) {
case 'ride\\library\\orm\\entry\\constraint\\EntryConstraint':
case 'ride\\library\\validation\\constraint\\GenericConstraint':
break;
default:
$validationConstraint = null;
}
}
$optionTypes = array('option', 'select', 'object');
$propertyTypes = array('tags', 'assets', 'label', 'geo');
$fields = $meta->getFields();
foreach ($fields as $fieldName => $field) {
if ($this->log) {
$this->log->logDebug('Generating field ' . $fieldName);
}
if (isset($this->omittedFields[$fieldName])) {
continue;
}
if (isset($this->hiddenFields[$fieldName])) {
$builder->addRow($fieldName, 'hidden');
continue;
}
$type = $field->getOption('scaffold.form.type');
if ($type) {
$isOptionType = in_array($type, $optionTypes);
} else {
$isOptionType = false;
}
$label = null;
$description = null;
$this->getLabel($options['translator'], $field, $label, $description);
if ($validationConstraint) {
$filters = $validationConstraint->getFilters($fieldName);
$validators = $validationConstraint->getValidators($fieldName);
} else {
$filters = array();
$validators = array();
}
if (in_array($type, $propertyTypes) || (!$isOptionType && !$field instanceof RelationField)) {
$this->addPropertyRow($builder, $field, $label, $description, $filters, $validators, $options, $type);
continue;
}
if (isset($this->fieldDepths[$fieldName])) {
$depth = $this->fieldDepths[$fieldName];
} else {
$depth = $this->depth;
}
if ($isOptionType || (!$type && $depth == 0)) {
$this->addOptionRow($builder, $field, $label, $description, $filters, $validators, $options, $type);
continue;
}
$this->addComponentRow($builder, $field, $label, $description, $filters, $validators, $options, $depth);
}
}
/**
* Adds a row for a property field to the form
* @param \ride\library\form\FormBuilder $builder Instance of the form builder
* @param \ride\library\orm\definition\field\ModelField $field Field to add
* @param string $label Label for the field
* @param string $description Description of the field
* @param array $filters Array with the filters for the property
* @param array $validators Array with the validators for the property
* @param array $options Extra options from the controller
* @param string $type Type of the row, defaults to the field type
* @return null
*/
protected function addPropertyRow(FormBuilder $builder, ModelField $field, $label, $description, array $filters, array $validators, array $options, $type = null) {
if (!$type) {
$type = $field->getType();
}
$rowOptions = array(
'label' => $label,
'description' => $description,
'filters' => $filters,
'attributes' => array(),
'localized' => $field->isLocalized(),
'locale' => $this->locale,
'order' => $field instanceof HasManyField && $field->isOrdered(),
);
$fieldDependency = $this->getFieldDependency($field);
if ($fieldDependency) {
$rowOptions['attributes']['class'] = $fieldDependency;
}
if ($type == 'boolean') {
$rowOptions['attributes']['data-toggle-dependant'] = 'option-' . $field->getName();
} elseif ($type == 'float') {
$type = 'number';
$rowOptions['attributes']['step'] = 'any';
} elseif ($type == 'datetime') {
$type = 'component';
$rowOptions['component'] = new DateTimeComponent();
} elseif ($type == 'date') {
$rowOptions['round'] = true;
} elseif ($type == 'seconds') {
$type = 'time';
$rowOptions['seconds'] = true;
$rowOptions['hours'] = false;
} elseif ($type == 'label') {
$decorator = $field->getOption('scaffold.form.decorator');
if ($decorator) {
if (strpos($decorator, '#')) {
list($interface, $id) = explode('#', $decorator, 2);
} else {
$interface = $decorator;
$id = null;
}
$dependencyInjector = $this->model->getOrmManager()->getDependencyInjector();
$rowOptions['decorator'] = $dependencyInjector->get($interface, $id);
$rowOptions['html'] = true;
} elseif ($field instanceof RelationField) {
$orm = $this->model->getOrmManager();
$relationModel = $orm->getModel($field->getRelationModelName());
$entryFormatter = $orm->getEntryFormatter();
$format = $relationModel->getMeta()->getFormat('title');
$decorator = $field->getOption('scaffold.form.decorator');
$rowOptions['decorator'] = new EntryFormatDecorator($entryFormatter, $format);
}
} elseif ($type == 'file' || $type == 'image') {
$path = $field->getOption('upload.path');
if ($path) {
$path = str_replace('%application%', $options['fileBrowser']->getApplicationDirectory()->getAbsolutePath(), $path);
$path = str_replace('%public%', $options['fileBrowser']->getPublicDirectory()->getAbsolutePath(), $path);
$rowOptions['path'] = $options['fileBrowser']->getFileSystem()->getFile($path);
}
} elseif ($type == 'tags') {
$urlSuffix = '?list=1&fields[taxonomy-terms]=&filter[match][name]=%term%';
$vocabulary = $field->getOption('taxonomy.vocabulary');
if ($vocabulary) {
if (is_numeric($vocabulary)) {
$urlSuffix .= '&filter[exact][vocabulary]=' . $vocabulary;
} else {
$urlSuffix .= '&filter[exact][vocabulary.slug]=' . $vocabulary;
}
}
$rowOptions['handler'] = new OrmTagHandler($this->model->getOrmManager(), $vocabulary);
$rowOptions['autocomplete.url'] = $this->web->getUrl('api.orm.entry.index', array('type' => 'taxonomy-terms')) . $urlSuffix;
$rowOptions['autocomplete.type'] = 'jsonapi';
} elseif ($type == 'assets') {
$rowOptions['multiple'] = $field instanceof HasManyField;
$folder = $field->getOption('assets.folder');
if ($folder) {
$rowOptions['folder'] = $folder;
}
} elseif ($type == 'geo') {
$geoType = $field->getOption('geo.type');
if (strpos($geoType, ',')) {
$geoType = explode(',', $geoType);
}
$rowOptions['multiple'] = $field instanceof HasManyField;
$rowOptions['filter'] = $field->getOption('geo.filter');
$rowOptions['type'] = $geoType;
}
if ($type != 'label') {
$rowOptions['validators'] = $validators;
}
if ($type == 'tags' || $type == 'geo') {
foreach ($validators as $validator) {
if ($validator instanceof SizeValidator) {
$rowOptions['autocomplete.max.items'] = $validator->getOption('maximum', 0);
}
}
}
$builder->addRow($field->getName(), $type, $rowOptions);
}
/**
* Adds a option row for a (relation) field to the form
* @param \ride\library\form\FormBuilder $builder Instance of the form builder
* @param \ride\library\orm\definition\field\ModelField $field Field to add
* @param string $label Label for the field
* @param string $description Description of the field
* @param array $filters Array with the filters for the property
* @param array $validators Array with the validators for the property
* @param array $options Extra options from the controller
* @param string $type Type detected to use as widget or row type
* @return null
*/
protected function addOptionRow(FormBuilder $builder, ModelField $field, $label, $description, array $filters, array $validators, array $options, $type) {
$options = $this->ormService->getFieldInputOptions($this->model, $field, $options['translator'], $options['data']);
if ($type == 'object') {
$widget = 'option';
} else {
$widget = $type;
}
$widget = $field->getOption('scaffold.form.widget', $widget);
$rowOptions = array(
'label' => $label,
'description' => $description,
'options' => $options,
'attributes' => array(
'data-toggle-dependant' => 'option-' . $field->getName(),
),
'multiple' => $field instanceof HasManyField,
'localized' => $field->isLocalized(),
'filters' => $filters,
'validators' => $validators,
'widget' => $widget,
);
$fieldDependency = $this->getFieldDependency($field);
if ($fieldDependency) {
$rowOptions['attributes']['class'] = $fieldDependency;
}
if (!$field instanceof PropertyField) {
$this->proxy[$field->getName()] = true;
$rowOptions['order'] = $rowOptions['multiple'] && $field->isOrdered();
$type = 'option';
}
if (!$rowOptions['multiple'] && $rowOptions['widget'] != 'option') {
$rowOptions['options'] = array('' => null) + $rowOptions['options'];
}
$builder->addRow($field->getName(), $type, $rowOptions);
}
/**
* Adds a select row for a relation field to the form
* @param \ride\library\form\FormBuilder $builder Instance of the form builder
* @param \ride\library\orm\definition\field\ModelField $field Field to add
* @param string $label Label for the field
* @param string $description Description of the field
* @param array $options Extra options from the controller
* @param integer $depth Depth for the relation fields
* @return null
*/
protected function addComponentRow(FormBuilder $builder, ModelField $field, $label, $description, array $filters, array $validators, array $options, $depth) {
$fieldName = $field->getName();
$relationModel = $this->model->getRelationModel($fieldName);
$relationMeta = $this->model->getMeta()->getRelationMeta($fieldName);
$component = $field->getOption('scaffold.form.component');
if (!$component) {
$component = $relationModel->getMeta()->getOption('scaffold.component');
}
if ($component) {
$formComponent = new $component($this->web, $this->securityManager, $this->ormService, $relationModel);
} else {
$formComponent = new self($this->web, $this->securityManager, $this->ormService, $relationModel);
}
if ($formComponent instanceof self) {
$formComponent->setDepth($depth - 1);
$formComponent->setLocale($this->locale);
$formComponent->setLog($this->log);
if ($relationMeta && !$relationMeta->isHasManyAndBelongsToMany()) {
$relationField = $relationMeta->getForeignKey();
if (!is_array($relationField)) {
$relationField = array($relationField);
}
foreach ($relationField as $omitField) {
$formComponent->omitField($omitField);
}
}
}
$rowOptions = array(
'label' => $label,
'description' => $description,
'filters' => $filters,
'validators' => $validators,
'attributes' => array(),
'localized' => $field->isLocalized(),
);
$fieldDependency = $this->getFieldDependency($field);
if ($fieldDependency) {
$rowOptions['attributes']['class'] = $fieldDependency;
}
if ($field instanceof BelongsToField) {
$type = 'component';
$rowOptions['component'] = $formComponent;
} else {
$type = 'collection';
$rowOptions['type'] = 'component';
$rowOptions['options'] = array(
'component' => $formComponent,
);
$option = $field->getOption('scaffold.form.collection.add', true);
if (!Boolean::getBoolean($option)) {
$rowOptions['disable_add'] = true;
}
$option = $field->getOption('scaffold.form.collection.remove', true);
if (!Boolean::getBoolean($option)) {
$rowOptions['disable_remove'] = true;
}
$rowOptions['order'] = $field instanceof HasManyField && $field->isOrdered();
}
$builder->addRow($fieldName, $type, $rowOptions);
}
/**
* Gets the label and description from the field
* @param \ride\library\i18n\translator\Translator $translator
* @param \ride\library\orm\definition\field\ModelField $field
* @param string $label
* @param string $description
* @return null
*/
protected function getLabel(Translator $translator, ModelField $field, &$label, &$description) {
$label = $field->getOption('label.name');
if ($label) {
$label = $translator->translate($label);
} else {
$label = ucfirst($field->getName());
}
$description = $field->getOption('label.description');
if ($description) {
$description = $translator->translate($description);
}
}
protected function getFieldDependency(ModelField $field) {
$dependant = $field->getOption('scaffold.form.dependant');
if (!$dependant) {
return null;
}
if (strpos($dependant, '-')) {
list($dependantField, $dependantValue) = explode('-', $dependant, 2);
} else {
$dependantField = $dependant;
$dependantValue = '1';
}
return 'option-' . $dependantField . ' option-' . $dependantField . '-' . $dependantValue;
}
}