This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
/
RockMigrations.module.php
1931 lines (1694 loc) · 54 KB
/
RockMigrations.module.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
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace ProcessWire;
/**
* RockMigrations Module
*
* @author Bernhard Baumrock, 08.01.2019
* @license Licensed under MIT
* @link https://www.baumrock.com
*/
class RockMigrations extends WireData implements Module {
private $module;
public $data;
public static function getModuleInfo() {
return [
'title' => 'RockMigrations',
'version' => '0.0.28',
'summary' => 'Module to handle Migrations inside your Modules easily.',
'autoload' => false,
'singular' => false,
'icon' => 'bolt',
];
}
public function init() {
// load the RockMigration Object Class
require_once('RockMigration.class.php');
// new WireData object to store runtime data of migrations
// see the demo module how to use this
$this->data = new WireData();
}
/**
* Execute downgrade of given version
*
* @param string $version
* @return void
*/
public function down($version) {
// check if module is set
if(!$this->module) throw new WireException("Please set the module first: setModule(\$yourmodule)");
// get migration
$migration = $this->getMigration($version);
if(!$migration) throw new WireException("Migration $version not found");
// now we execute the upgrade
$prev = @$migration->getPrev()->version;
$this->executeUpgrade($version, $prev);
}
/**
* Execute the upgrade from one version to another
*
* Does also execute on downgrades.
* If a module is set, we execute this upgrade on that module and not on the current.
*
* @param string $from
* @param string $to
* @param Module|string $module
*
* @return int number of migrations that where executed
*/
public function execute($from, $to, $module = null) {
$currentModule = $this->module;
if($module) {
$module = $this->modules->get((string)$module);
if(!$module) throw new WireException("Module not found!");
$this->module = $module;
}
// check if module is set
if(!$this->module) throw new WireException("Module invalid or not set!");
// get migrations
$migrations = $this->getMigrations();
// check mode and log request
$mode = version_compare($from, $to) > 0 ? 'downgrade' : 'upgrade';
$this->log("Executing $mode $from --> $to for module " . $this->module);
// early exit if no migrations
$count = 0;
if(!count($migrations)) return $count;
// flip array and numbers for downgrades
if($mode == 'downgrade') {
$migrations = array_reverse($migrations);
$tmp = $from;
$from = $to;
$to = $tmp;
}
// make sure we execute the migrations on the default language.
// this is necessary that field values are set in the default language,
// eg. when creating a new page and setting the title of a multi-lang page.
$lang = $this->user->language;
if($this->languages) $this->user->language = $this->languages->getDefault();
// now execute all available upgrades step by step
foreach($migrations as $version) {
// check if migration is part of the upgrade
if(version_compare($version, $from) >= 1
AND version_compare($version, $to) <= 0) {
// this migration is part of the upgrade, so run it
// this either calls upgrade() or downgrade() of the php file
// make sure outputformatting is off for all migrations
$this->pages->of(false);
// execute the migrations
$migration = $this->getMigration($version);
$this->log("Executing $mode {$migration->file}");
$migration->{$mode}->__invoke($this);
// increase count
$count++;
}
}
// change language back to original
$this->user->setAndSave('language', $lang);
// reset the module to it's initial state
if($module) $this->module = $currentModule;
return $count;
}
/**
* Execute all Upgrade Scripts on Installation
*
* @return void
*/
public function executeInstall() {
// check if module is set
if(!$this->module) throw new WireException("Please set the module first: setModule(\$yourmodule)");
$version = $this->modules->getModuleInfo($this->module)['version'];
$versionStr = $this->modules->formatVersion($version);
return $this->executeUpgrade(null, $versionStr);
}
/**
* Execute all Downgrade Scripts on Uninstallation
*
* @return void
*/
public function executeUninstall() {
// check if module is set
if(!$this->module) throw new WireException("Please set the module first: setModule(\$yourmodule)");
$version = $this->modules->getModuleInfo($this->module)['version'];
$versionStr = $this->modules->formatVersion($version);
return $this->executeUpgrade($versionStr, null);
}
/**
* for backwards compatibility
*/
public function executeUpgrade($from, $to, $module = null) {
return $this->execute($from, $to, $module);
}
/**
* This will add a hook after Modules::refresh
* It will be executed only for superusers!
*
* Usage:
* In your module's init() use
* $rm->fireOnRefresh($this, "migrate");
*
* @return void
*/
public function fireOnRefresh($module, $method) {
if(!$this->wire->user->isSuperuser()) return;
$this->wire->addHookAfter("Modules::refresh", $module, $method);
}
/**
* Get Migration Object from Version Number
*
* @param string $version
* @return RockMigration
*/
public function getMigration($version) {
$migration = new RockMigration();
$migration->version = $version;
$migration->object = $this;
// find according php file
$file = $this->getMigrationsPath().$version.".php";
$upgrade = function(){};
$downgrade = function(){};
$migration->file = null;
if(is_file($file)) {
include($file);
$migration->file = $file;
}
$migration->upgrade = $upgrade;
$migration->downgrade = $downgrade;
return $migration;
}
/**
* Get all migrations of one module
*
* @param Module $module
* @return array
*/
public function getMigrations() {
$migrations = [];
// find all files in the RockMigrations folder of the module
$files = $this->files->find($this->getMigrationsPath(), [
'extensions' => ['php']
]);
// build an array of migration
foreach($files as $file) {
$info = pathinfo($file);
$migrations[] = $info['filename'];
}
// sort array according to version numbers
// see https://i.imgur.com/F52wGT9.png
usort($migrations, 'version_compare');
return $migrations;
}
/**
* Get the module's migration path
*
* @return void
*/
public function ___getMigrationsPath() {
return $this->config->paths($this->module) . $this->className() . "/";
}
/**
* Call init() of pageclass if it exists
*
* Usage:
* The preferred usage is to use the classname to load the class.
* This makes sure that the init() is triggered even if no page exists.
*
* In init() of a module:
* $rm->initPageClass("MyCustomPageClass");
*
* Usage on existing pages:
* $rm->initPageClass("/foo");
*
* @return void
*/
public function initPageClass($data, $options = []) {
$opt = $this->wire(new WireData()); /** @var WireData $opt */
$opt->setArray([
'method' => 'init',
'namespace' => 'ProcessWire',
]);
$opt->setArray($options);
// load existing page or setup a new one
try {
$page = $this->wire->pages->get((string)$data);
} catch (\Throwable $th) {
$this->wire->classLoader->loadClass($data);
$class = "\\{$opt->namespace}\\$data";
$page = $this->wire(new $class());
}
// trigger $page->init() or $page->ready()
if(!method_exists($page, $opt->method)) return;
$page->{$opt->method}();
}
/**
* Call ready() of pageclass if it exists
*
* See initPageClass() for docs.
*
* @return void
*/
public function readyPageClass($data) {
$this->initPageClass($data, 'ready');
}
/**
* Set module that is controlled
*
* @param string|Module $module
* @return void
*/
public function setModule($module) {
$module = $this->modules->get((string)$module);
if(!$module instanceof Module) throw new WireException("This is not a valid Module!");
$this->module = $module;
return $this;
}
/**
* Test upgrade for given version
*
* This will execute the downgrade and then the upgrade of only this version.
*
* @param string $version
* @return void
*/
public function test($version) {
$this->down($version);
$this->modules->refresh();
$this->up($version);
}
/**
* For backwards compatibility
*/
public function testUpgrade($version) {
$this->test($version);
}
/**
* Trigger method of class if it exists
*
* Usage:
*
* In your module's init()
* $rm->trigger("\Foo\Bar", "init");
*
* In your module's ready()
* $rm->trigger("\Foo\Bar", "init");
*
* @return void
*/
public function trigger($class, $method) {
$obj = new $class();
if(method_exists($obj, $method)) $obj->$method();
}
/**
* Execute upgrade of given version
*
* @param string $version
* @return void
*/
public function up($version) {
// check if module is set
if(!$this->module) throw new WireException("Please set the module first: setModule(\$yourmodule)");
// get migration
$migration = $this->getMigration($version);
if(!$migration) throw new WireException("Migration $version not found");
// now we execute the upgrade
$prev = @$migration->getPrev()->version;
$this->executeUpgrade($prev, $version);
}
/* ##################### RockMigrations API Methods ##################### */
/* ##### fields ##### */
/**
* Add field to template
*
* @param Field|string $field
* @param Template|string $template
* @return void
*/
public function addFieldToTemplate($field, $template, $afterfield = null, $beforefield = null) {
$field = $this->getField($field);
$template = $this->getTemplate($template, false);
if(!$template) return;
$afterfield = $this->getField($afterfield, false);
$beforefield = $this->getField($beforefield, false);
$fg = $template->fieldgroup; /** @var Fieldgroup $fg */
if($afterfield) $fg->insertAfter($field, $afterfield);
elseif($beforefield) $fg->insertBefore($field, $beforefield);
else $fg->add($field);
// add end field for fieldsets
if($field->type instanceof FieldtypeFieldsetOpen
AND !$field->type instanceof FieldtypeFieldsetClose) {
$closer = $field->type->getFieldsetCloseField($field, false);
$this->addFieldToTemplate($closer, $template, $field);
}
$fg->save();
}
/**
* Add fields to template.
*
* Simple:
* $rm->addFieldsToTemplate(['field1', 'field2'], 'yourtemplate');
*
* Add fields at special positions:
* $rm->addFieldsToTemplate([
* 'field1',
* 'field4' => 'field3', // this will add field4 after field3
* ], 'yourtemplate');
*
* @param array $fields
* @param string $template
* @return void
*/
public function addFieldsToTemplate($fields, $template) {
foreach($fields as $k=>$v) {
// if the key is an integer, it's a simple field
if(is_int($k)) $this->addFieldToTemplate((string)$v, $template);
else $this->addFieldToTemplate((string)$k, $template, $v);
}
}
/**
* Add matrix item to given field
* @param Field|string $field
* @param string $name
* @param array $data
* @return Field|null
*/
public function addMatrixItem($field, $name, $data) {
if(!$field = $this->getField($field, false)) return;
// get number
$n = 1;
while(array_key_exists("matrix{$n}_name", $field->getArray())) $n++;
$prefix = "matrix{$n}_";
$field->set($prefix."name", $name);
$field->set($prefix."sort", $n);
foreach($this->getMatrixDataArray($data) as $key => $val) {
// eg set matrix1_label = ...
$field->set($prefix.$key, $val);
if($key === "fields") {
$tpl = $this->getRepeaterTemplate($field);
$this->addFieldsToTemplate($val, $tpl);
}
}
$field = $this->resetMatrixRepeaterFields($field);
$field->save();
return $field;
}
/**
* Change type of field
* @param Field|string $field
* @param string $type
* @param bool $keepSettings
* @return Field
*/
public function changeFieldtype($field, $type, $keepSettings = true) {
$field = $this->getField($field);
// if type is already set, return early
if($field->type == $type) return $field;
// change type and save field
$field->type = $type;
$this->fields->changeFieldtype($field, $keepSettings);
$field->save();
return $field;
}
/**
* Create a field of the given type
*
* @param string $name
* @param string $type
* @param array $options
* @return Field
*/
public function createField($name, $typename, $options = null) {
$field = $this->getField($name, false);
if(!$field) {
// setup fieldtype
$type = $this->modules->get($typename);
if(!$type) {
// shortcut types are possible, eg "text" for "FieldtypeText"
$type = "Fieldtype".ucfirst($typename);
$type = $this->modules->get($type);
if(!$type) throw new WireException("Invalid Fieldtype");
}
// create the new field
if(strtolower($name) !== $name) throw new WireException("Fieldname must be lowercase!");
$name = strtolower($name);
$field = $this->wire(new Field());
$field->type = $type;
$field->name = $name;
$field->save();
// create end field for fieldsets
if($field->type instanceof FieldtypeFieldsetOpen) {
$field->type->getFieldsetCloseField($field, true);
}
// this will auto-generate the repeater template
if($field->type instanceof FieldtypeRepeater) {
$field->type->getRepeaterTemplate($field);
}
}
// set options
if($options) $field = $this->setFieldData($field, $options);
return $field;
}
/**
* Delete the given field
*
* @param string $name
* @return void
*/
public function deleteField($name) {
$field = $this->getField($name, false);
if(!$field) return;
// delete _END field for fieldsets first
if($field->type instanceof FieldtypeFieldsetOpen) {
$closer = $field->type->getFieldsetCloseField($field, false);
$this->deleteField($closer);
}
// make sure we can delete the field by removing all flags
$field->flags = Field::flagSystemOverride;
$field->flags = 0;
// remove the field from all fieldgroups
foreach($this->fieldgroups as $fieldgroup) {
/** @var Fieldgroup $fieldgroup */
$fieldgroup->remove($field);
$fieldgroup->save();
}
return $this->fields->delete($field);
}
/**
* Delete given fields
*
* @param array $fields
* @return void
*/
public function deleteFields($fields) {
foreach($fields as $field) $this->deleteField($field);
}
/**
* Delete template overrides for the given field
*
* Example usage:
* Delete custom field width for 'myfield' and 'mytemplate':
* $rm->deleteFieldTemplateOverrides('myfield', [
* 'mytemplate' => ['columnWidth'],
* ]);
*
* @param Field|string $field
* @param array $templatesettings
* @return void
*/
public function deleteFieldTemplateOverrides($field, $templatesettings) {
$field = $this->getField($field);
// loop data
foreach($templatesettings as $tpl=>$val) {
// get template
$template = $this->templates->get((string)$tpl);
if(!$template) throw new WireException("Template $tpl not found");
// set field data in template context
$fg = $template->fieldgroup;
$data = $fg->getFieldContextArray($field->id);
foreach($val as $setting) unset($data[$setting]);
$fg->setFieldContextArray($field->id, $data);
$fg->saveContext();
}
}
/**
* Get field by name
*
* @param Field|string $name
* @return mixed
*/
public function getField($name, $exception = null) {
if($name AND !is_string($name) AND !$name instanceof Field) {
$func = @debug_backtrace()[1]['function'];
throw new WireException("Invalid type set for field in $func");
}
$field = $this->fields->get((string)$name);
// return field when found or no exception
if($field) return $field;
if($exception === false) return;
// field was not found, throw exception
if(!$exception) $exception = "Field $name not found";
throw new WireException($exception);
}
/**
* Move one field after another
*
* @param Field|string $field
* @param Field|string $after
* @param Template|string $template
* @return void
*/
public function moveFieldAfter($field, $after, $template) {
$this->addFieldToTemplate($field, $template, $after);
}
/**
* Move one field before another
*
* @param Field|string $field
* @param Field|string $before
* @param Template|string $template
* @return void
*/
public function moveFieldBefore($field, $before, $template) {
$this->addFieldToTemplate($field, $template, null, $before);
}
/**
* Remove Field from Template
*
* @param Field|string $field
* @param Template|string $template
* @param bool $force
* @return void
*/
public function removeFieldFromTemplate($field, $template, $force = false) {
$field = $this->getField($field, false);
if(!$field) return;
$template = $this->templates->get((string)$template);
if(!$template) return;
$fg = $template->fieldgroup; /** @var Fieldgroup $fg */
// remove global flag to force deletion
if($force) $field->flags = 0;
$fg->remove($field);
$fg->save();
}
/**
* See method above
*/
public function removeFieldsFromTemplate($fields, $template, $force = false) {
foreach($fields as $field) $this->removeFieldFromTemplate($field, $template, $force);
}
/**
* Remove matrix item from field
* @param Field|string $field
* @param string $name
* @return Field|null
*/
public function removeMatrixItem($field, $name) {
if(!$field = $this->getField($field, false)) return;
$info = $field->type->getMatrixTypesInfo($field, ['type'=>$name]);
if(!$info) return;
// reset all properties of that field
foreach($field->getArray() as $prop=>$val) {
if(strpos($prop, $info['prefix']) !== 0) continue;
$field->set($prop, null);
}
$field = $this->resetMatrixRepeaterFields($field);
$field->save();
return $field;
}
/**
* Rename this field
* @return Field|false
*/
public function renameField($oldname, $newname) {
$field = $this->getField($oldname, false);
if(!$field) return false;
// the new field must not exist
$newfield = $this->getField($newname, false);
if($newfield) throw new WireException("Field $newname already exists");
// change the old field
$field->name = $newname;
$field->save();
}
/**
* Set data of a field
*
* If a template is provided the data is set in template context only.
* You can also provide an array of templates.
*
* Multilang is also possible:
* $rm->setFieldData('yourfield', [
* 'label' => 'foo', // default language
* 'label1021' => 'bar', // other language
* ]);
*
* @param Field|string $field
* @param array $data
* @param Template|array|string $template
* @return void
*/
public function setFieldData($field, $data, $template = null) {
$field = $this->getField($field);
// prepare data array
foreach($data as $key=>$val) {
// this makes it possible to set the template via name
if($key === "template_id") {
$data[$key] = $this->templates->get($val)->id;
}
// support repeater field array
if($key === "repeaterFields") {
$fields = $data[$key];
foreach($fields as $i=>$_field) {
$fields[$i] = $this->fields->get((string)$_field)->id;
}
$data[$key] = $fields;
// add fields to repeater template
if($tpl = $this->getRepeaterTemplate($field)) {
$this->addFieldsToTemplate($fields, $tpl);
}
}
}
// set data
if(!$template) {
// set field data directly
foreach($data as $k=>$v) $field->{$k} = $v;
}
else {
// make sure the template is set as array of strings
if(!is_array($template)) $template = [(string)$template];
foreach($template as $t) {
$tpl = $this->templates->get((string)$t);
if(!$tpl) throw new WireException("Template $t not found");
// set field data in template context
$fg = $tpl->fieldgroup;
$current = $fg->getFieldContextArray($field->id);
$fg->setFieldContextArray($field->id, array_merge($current, $data));
$fg->saveContext();
}
}
// Make sure Table field actually updates database schema
if ($field->type == "FieldtypeTable") {
$fieldtypeTable = $field->getFieldtype();
$fieldtypeTable->_checkSchema($field, true); // Commit changes
}
$field->save();
return $field;
}
/**
* Set the language value of the given field
*
* $rm->setFieldLanguageValue("/admin/therapy", 'title', [
* 'default' => 'Therapie',
* 'english' => 'Therapy',
* ]);
*
* @param Page|string $page
* @param Field|string $field
* @param array $data
* @return void
*/
public function setFieldLanguageValue($page, $field, $data) {
$page = $this->pages->get((string)$page);
if(!$page->id) throw new WireException("Page not found!");
$page->of(false);
$field = $this->getField($field);
// set field value for all provided languages
foreach($data as $lang=>$val) {
$lang = $this->languages->get($lang);
if(!$lang->id) continue;
$page->{$field}->setLanguageValue($lang, $val);
}
$page->save();
}
/**
* Set options of an options field via string
*
* $rm->setFieldOptionsString("yourfield", "
* 1=foo|My Foo Option
* 2=bar|My Bar Option
* ");
*
* @param Field|string $name
* @param string $options
* @return void
*/
public function setFieldOptionsString($name, $options, $removeOthers = false) {
$field = $this->getField($name);
$manager = $this->wire(new SelectableOptionManager());
// now set the options
$manager->setOptionsString($field, $options, $removeOthers);
$field->save();
return $field;
}
/**
* Set field order at given template
*
* The first field is always the reference for all other fields.
*
* @param array $fields
* @param Template|string $name
* @return void
*/
public function setFieldOrder($fields, $name) {
$template = $this->templates->get((string)$name);
if(!$template) throw new WireException("Template $name not found");
// make sure that all fields exist
foreach($fields as $i=>$field) {
if(!$this->fields->get($field)) unset($fields[$i]);
}
$fields = array_values($fields); // reset indices
foreach($fields as $i => $field) {
if(!$i) continue;
$this->addFieldToTemplate($field, $template, $fields[$i-1]);
}
}
/**
* Set matrix item data
* @param Field|string $field
* @param string $name
* @param array $data
* @return Field|null
*/
public function setMatrixItemData($field, $name, $data) {
if(!$field = $this->getField($field, false)) return;
$info = $field->type->getMatrixTypesInfo($field, ['type'=>$name]);
if(!$info) return;
foreach($this->getMatrixDataArray($data) as $key => $val) {
// eg set matrix1_label = ...
$field->set($info['prefix'].$key, $val);
if($key === "fields") {
$tpl = $this->getRepeaterTemplate($field);
$this->addFieldsToTemplate($val, $tpl);
}
}
$field = $this->resetMatrixRepeaterFields($field);
$field->save();
return $field;
}
/**
* Set items of a RepeaterMatrix field
*
* If wipe is set to TRUE it will wipe all existing matrix types before
* setting the new ones. Otherwise it will override settings of old types
* and add the type to the end of the matrix if it does not exist yet.
*
* CAUTION: wipe = true will also delete all field data stored in the
* repeater matrix fields!!
*
* Usage:
* $rm->setMatrixItems('your_matrix_field', [
* 'foo' => [
* 'label' => 'foo label',
* 'fields' => ['field1', 'field2'],
* ],
* 'bar' => [
* 'label' => 'bar label',
* 'fields' => ['field1', 'field3'],
* ],
* ], true);
*
* @param Field|string $field
* @param array $items
* @param bool $wipe
* @return Field|null
*/
public function setMatrixItems($field, $items, $wipe = false) {
if(!$this->modules->isInstalled('FieldtypeRepeaterMatrix')) return;
if(!$field = $this->getField($field, false)) return;
// get all matrix types of that field
$types = $field->type->getMatrixTypes();
// if wipe is turned on we remove all existing items
// this is great when you want to control the matrix solely by migrations
if($wipe) {
foreach($types as $type => $v) $this->removeMatrixItem($field, $type);
}
// loop all provided items
foreach($items as $name => $data) {
$type = $field->type->getMatrixTypeByName($name);
if(!$type) $field = $this->addMatrixItem($field, $name, $data);
else $this->setMatrixItemData($field, $name, $data);
}
return $field;
}
/* ##### templates ##### */
/**
* Allow given child for given parent
*/
public function addAllowedChild($child, $parent) {
$child = $this->getTemplate($child);
$parent = $this->getTemplate($parent);
$childs = $parent->childTemplates;
$childs[] = $child;
$this->setTemplateData($parent, ['childTemplates' => $childs]);
}
/**
* Add role to template
*
* Usage:
* $rm->addRoleToTemplate(["view", "edit"], "myrole", "mytemplate");
*
* @param mixed $permission
* @param mixed $role
* @param mixed $tpl
* @return void
*/
public function addRoleToTemplate($permission, $role, $tpl) {
if(is_array($permission)) {
foreach($permission as $p) $this->addRoleToTemplate($p, $role, $tpl);
return;
}
$tpl = $this->wire->templates->get((string)$tpl);
$role = $this->wire->roles->get((string)$role);
if(!$tpl) return;
if(!$role) return;
$tpl->useRoles = 1;
$prop = "roles";
if($permission == "edit") $prop = "editRoles";
if($permission == "add") $prop = "addRoles";
if($permission == "create") $prop = "createRoles";
$arr = $this->getRoleArray($tpl->$prop);
$newArray = array_merge($arr, [(int)(string)$role]);
$tpl->$prop = $newArray;
$tpl->save();
}
/**
* Create a new ProcessWire Template
*
* @param string $name
* @param bool $addTitlefield
* @return void
*/
public function createTemplate($name, $addTitlefield = true) {
$t = $this->templates->get((string)$name);
if($t) return $t;
// create new fieldgroup
$fg = $this->wire(new Fieldgroup());
$fg->name = $name;
$fg->save();
// create new template
$t = $this->wire(new Template());
$t->name = $name;
$t->fieldgroup = $fg;
$t->save();