This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
RockMigrations.module.php
2756 lines (2453 loc) · 82.4 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 static function getModuleInfo() {
return [
'title' => 'RockMigrations',
'version' => '0.0.86',
'summary' => 'Module to handle Migrations inside your Modules easily.',
'autoload' => true,
'singular' => true,
'icon' => 'bolt',
];
}
public function init() {
// load the RockMigration Object Class
require_once('RockMigration.class.php');
// set API variable
$this->wire('rockmigrations', $this);
// attach hooks
$this->loadFilesOnDemand();
}
/**
* Add script to pw $config
* Usage:
* $rm->addScript(__DIR__."/Foo.js");
*/
public function addScript($path, $timestamp = true) {
if(!is_file($path)) return;
$path = Paths::normalizeSeparators($path);
$config = $this->wire->config;
$url = str_replace($config->paths->root, $config->urls->root, $path);
$m = $timestamp ? "?m=".filemtime($path) : '';
$this->wire->config->scripts->add($url.$m);
}
/**
* Add style to pw $config
* Usage:
* $rm->addStyle(__DIR__."/Foo.js");
*/
public function addStyle($path, $timestamp = true) {
if(!is_file($path)) return;
$path = Paths::normalizeSeparators($path);
$config = $this->wire->config;
$url = str_replace($config->paths->root, $config->urls->root, $path);
$m = $timestamp ? "?m=".filemtime($path) : '';
$this->wire->config->styles->add($url.$m);
}
/**
* Register autoloader for all classes in given folder
* This will NOT trigger init() or ready()
* You can also use $rm->initClasses() with setting autoload=true
*/
public function autoload($path, $namespace) {
$path = Paths::normalizeSeparators($path);
spl_autoload_register(function($class) use($path, $namespace) {
if(strpos($class, "$namespace\\") !== 0) return;
$name = substr($class, strlen($namespace)+1);
$file = "$path/$name.php";
if(is_file($file)) require_once($file);
});
}
/**
* Execute downgrade of given version
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* 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
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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");
*
* In ready.php you can use it with a callback function:
* $rm->fireOnRefresh(function($event) use($rm) {
* $rm->deleteField(...);
* });
*
* @param Module $module module or callback
* @param string $method the method name to invoke
* @param int|array $priority options array for the hook; if you provide
* an integer value it will be casted to the hook priority ['priority'=>xxx]
*
* @return void
*/
public function fireOnRefresh($module, $method = null, $priority = []) {
// If flags are present dont attach hooks to Modules::refresh
// See the readme for more information!
if(defined("DontFireOnRefresh")) return;
if($this->wire->config->DontFireOnRefresh) return;
// attach the hook
if(is_int($priority)) $priority = ['priority'=>$priority];
if($module instanceof Module) {
$this->wire->addHookAfter("Modules::refresh", $module, $method, $priority);
}
elseif(is_callable($module)) {
$callback = $module;
$this->wire->addHookAfter("Modules::refresh", $callback, null, $priority);
}
}
/**
* Helper that returns a new Inputfield object from array syntax
*
* Usage:
* $f = $rm->getInputfield(['type'=>'markup', 'value'=>'foo']);
* $form->insertAfter($f, $form->get('title'));
*
* @return Inputfield
*/
public function getInputfield($array) {
$form = new InputfieldForm();
$form->add($array);
return $form->children()->first();
}
/**
* Get Migration Object from Version Number
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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() . "/";
}
/**
* Get page from data
* @return Page
*/
public function getPage($data) {
return $this->wire->pages->get((string)$data);
}
/**
* Get textformatter from name
* @return Textformatter
*/
public function getTextformatter($name) {
$formatter = $this->wire->modules->get("Textformatter".$name);
if(!$formatter) $formatter = $this->wire->modules->get($name);
return $formatter;
}
/**
* Create view files with include statement in templates folder
*
* Usage:
* Let's say we have a module "Foo"; Inside the module's path we have
* a "views" folder. In the module's fireOnRefresh() migration we simply add:
*
* public function migrate() {
* $rm = ...
* $rm->migrate(...); // migrate fields and templates
* $rm->includeViews($this);
* }
*
* This will look for php files in folder /path/to/your/module/views and create
* a php file in /site/templates that include()'s the related PHP file from
* within the modules folder. This means that you can manage the code of the
* template file from within your module without ever copying any files manually
* to the templates folder :)
*
* @return void
*/
public function includeViews($path) {
$config = $this->wire->config;
$files = $this->wire->files;
if($path instanceof Module) $path = $config->paths($path)."views";
foreach($files->find($path, ['extensions' => ['php']]) as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);
$url = str_replace($config->paths->root, '', $file);
$content = "<?php namespace ProcessWire;\n"
."// DONT CHANGE THIS FILE\n"
."// it is created automatically via RockMigrations\n"
."include(\$config->paths->root.'$url');\n";
file_put_contents($config->paths->templates.$name.".php", $content);
}
}
/**
* Trigger init() method of classes in this folder
*
* If autoload is set to TRUE it will attach a class autoloader before
* triggering the init() method. The autoloader is important so that we do
* not get any conflicts on the loading order of the classes. This could
* happen if we just used require() in here because then the loadind order
* would depend on the file names of loaded classes. This would cause problems
* if for example class BAR was dependent on class FOO which would not exist
* on load of BAR.
*
* @return void
*/
public function initClasses($path, $namespace = "ProcessWire", $autoload = true) {
if($autoload) $this->autoload($path, $namespace);
foreach($this->files->find($path, ['extensions' => ['php']]) as $file) {
$info = $this->info($file);
$class = $info->filename;
if($namespace) $class = "\\$namespace\\$class";
$tmp = new $class();
if(method_exists($tmp, "init")) $tmp->init();
// attach hooks for some magic methods
if(method_exists($tmp, "buildForm")) {
$this->wire->addHookAfter("ProcessPageEdit::buildForm", $tmp, "buildForm");
}
if(method_exists($tmp, "buildFormContent")) {
$this->wire->addHookAfter("ProcessPageEdit::buildFormContent", $tmp, "buildFormContent");
}
}
}
/**
* DEPRECATED - use initClasses() instead
*/
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}();
}
/**
* Load files on demand on local installation
*
* Usage: set $config->filesOnDemand = 'your.hostname.com' in your config file
*
* Make sure that this setting is only used on your local test config and not
* on a live system!
*
* @return void
*/
public function loadFilesOnDemand() {
if(!$host = $this->wire->config->filesOnDemand) return;
$hook = function(HookEvent $event) use($host) {
$config = $this->wire->config;
$file = $event->return;
// this makes it possible to prevent downloading at runtime
if(!$this->wire->config->filesOnDemand) return;
// convert url to disk path
if($event->method == 'url') {
$file = $config->paths->root.substr($file, strlen($config->urls->root));
}
// load file from remote if it does not exist
if(!file_exists($file)) {
$host = rtrim($host, "/");
$src = "$host/site/assets/files/";
$url = str_replace($config->paths->files, $src, $file);
$http = $this->wire(new WireHttp()); /** @var WireHttp $http */
try {
$http->download($url, $file);
} catch (\Throwable $th) {
// do not throw exception, show error message instead
$this->error($th->getMessage());
}
}
};
$this->addHookAfter("Pagefile::url", $hook);
$this->addHookAfter("Pagefile::filename", $hook);
}
/**
* Trigger ready() method of classes in this folder
* This will NOT load the classes - use autoload() or initClasses() before
* @return void
*/
public function readyClasses($path, $namespace = "ProcessWire") {
foreach($this->files->find($path, ['extensions' => ['php']]) as $file) {
$info = $this->info($file);
$class = $info->filename;
if($namespace) $class = "\\$namespace\\$class";
$tmp = new $class();
if(method_exists($tmp, "ready")) $tmp->ready();
}
}
/**
* DEPRECATED - use initClasses() instead
*/
public function readyPageClass($data) {
$this->initPageClass($data, 'ready');
}
/**
* Set the logo url of the backend logo (AdminThemeUikit)
* @return void
*/
public function setAdminLogoUrl($url) {
$this->setModuleConfig("AdminThemeUikit", ['logoURL' => $url]);
}
/**
* Set default options for several things in PW
*/
public function setDefaults($options = []) {
$opt = $this->wire(new WireData()); /** @var WireData $opt */
$opt->setArray([
'pagenameReplacements' => 'de',
'toggleBehavior' => 1,
]);
$opt->setArray($options);
// set german pagename replacements
$this->setPagenameReplacements($opt->pagenameReplacements);
// AdminThemeUikit settings
$this->setModuleConfig("AdminThemeUikit", [
// use consistent inputfield clicks
// see https://github.com/processwire/processwire/pull/169
'toggleBehavior' => $opt->toggleBehavior,
]);
}
/**
* 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;
}
/**
* Set page name from page title
*
* Usage:
* $rm->setPageNameFromTitle("basic-page");
*
* Make sure to install Page Path History module!
*
* @param mixed $object
*/
public function setPageNameFromTitle($template) {
$template = $this->getTemplate($template);
$tpl = "template=$template";
$this->addHookAfter("Pages::saveReady($tpl,id>0)", function(HookEvent $event) {
/** @var Page $page */
$page = $event->arguments(0);
$langs = $this->wire->languages;
if($langs) {
foreach($langs as $lang) {
$prop = $lang->isDefault() ? "name" : "name$lang";
$old = $page->get($prop);
$new = $page->getLanguageValue($lang, "title");
$new = $event->sanitizer->pageNameTranslate($new);
if($new AND $old!=$new) {
$page->set($prop, $new);
$this->message($this->_("Page name updated to $new ($lang->name)"));
}
}
}
else {
$old = $page->name;
$new = $event->sanitizer->pageNameTranslate($page->title);
if($new AND $old!=$new) {
$page->name = $new;
$this->message($this->_("Page name updated to $new"));
}
}
});
$this->addHookAfter("ProcessPageEdit::buildForm", function(HookEvent $event) use($template) {
$page = $event->object->getPage();
if($page->template != $template) return;
$form = $event->return;
if($f = $form->get('_pw_page_name')) {
$f->notes = $this->_('Page name will be set automatically from page title on save.');
}
});
}
/**
* Change current user to superuser
* When bootstrapped sometimes we get permission conflicts
* See https://processwire.com/talk/topic/458-superuser-when-bootstrapping/
* @return void
*/
public function sudo() {
$id = $this->wire->config->superUserPageID;
$this->wire->users->setCurrentUser($this->wire->users->get($id));
}
/**
* Test upgrade for given version
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* 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", "ready");
*
* @return void
*/
public function trigger($class, $method) {
$obj = new $class();
if(method_exists($obj, $method)) $obj->$method();
}
/**
* Execute upgrade of given version
* DEPRECATED SEE https://bit.ly/3lPWg3Q
*
* @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);
}
public function watch($file, $migrate = true, $options = []) {
return false;
}
/**
* Wrap fields of a form into a fieldset
*
* Usage:
* $rm->wrapFields($form, ['foo', 'bar'], [
* 'label' => 'your fieldset label',
* 'icon' => 'bolt',
* ]);
*
* @return InputfieldFieldset
*/
public function wrapFields(InputfieldWrapper $form, array $fields, array $fieldset) {
$_fields = [];
$last = false;
foreach($fields as $field) {
$f = $form->get((string)$field);
if($f instanceof Inputfield) {
$_fields[] = $f;
$last = $f;
}
}
if(!$last) return;
/** @var InputfieldFieldset $f */
$fs = $this->wire('modules')->get('InputfieldFieldset');
foreach($fieldset as $k=>$v) $fs->$k = $v;
$form->insertAfter($fs, $last);
// now remove fields from the form and add them to the fieldset
foreach($_fields as $f) {
$form->remove($f);
$fs->add($f);
}
return $fs;
}
/* ##################### 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, false);
if(!$field) return $this->log("Field $_field not found");
$template = $this->getTemplate($_template, false);
if(!$template) return $this->log("Template $_template not found");
$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
* @param bool $sortFields
* @return void
*/
public function addFieldsToTemplate($fields, $template, $sortFields = false) {
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);
}
if($sortFields) $this->setFieldOrder($fields, $template);
}
/**
* 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;
}
/**
* Add textformatter to given field
* You can set a template context as third parameter
* @param mixed $formatter formatter to add
* @param mixed $field to add the formatter to
* @return void
*/
public function addTextformatterToField($formatter, $field) {
$name = (string)$formatter;
$formatter = $this->getTextformatter($name);
if(!$formatter) return $this->log("Formatter $name not found");
$formatters = $this->getFieldData($field, "textformatters") ?: [];
$formatters = array_merge($formatters, [(string)$formatter]);
$this->setFieldData($field, [
'textformatters' => $formatters,
]);
}
/**
* 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) {
// handle special cases
if(is_string($typename)) {
// type 'page' does not work because it tries to get the page module
if(strtolower($typename) === 'page') $typename = "FieldtypePage";
}
// 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->label = $name; // set label (mandatory since ~3.0.172)
$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
*
* If parameter is a string we use it as selector for $fields->find()
*
* Usage:
* $rm->deleteFields("tags=MyModule");
*
* @param array|string $fields
* @return void
*/
public function deleteFields($fields) {
if(is_string($fields)) $fields = $this->wire->fields->find($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) return false;
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 false;
// field was not found, throw exception
if(!$exception) $exception = "Field $name not found";
throw new WireException($exception);
}
/**
* Get field data of field
* @return array
*/
public function getFieldData($field, $property = null) {
$field = $this->getField($field);
$arr = $field->getArray();
if(!$property) return $arr;
if(!array_key_exists($property, $arr)) return false;
return $arr[$property];