-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathTableController.php
More file actions
1691 lines (1527 loc) · 60.4 KB
/
TableController.php
File metadata and controls
1691 lines (1527 loc) · 60.4 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
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 plugin\admin\app\controller;
use Doctrine\Inflector\InflectorFactory;
use Illuminate\Database\Schema\Blueprint;
use plugin\admin\app\common\Layui;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Role;
use plugin\admin\app\model\Rule;
use plugin\admin\app\model\Option;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;
class TableController extends Base
{
/**
* 不需要鉴权的方法
* @var string[]
*/
protected $noNeedAuth = ['types'];
/**
* 浏览
* @return Response
* @throws Throwable
*/
public function index(): Response
{
return raw_view('table/index');
}
/**
* 查看表
* @param Request $request
* @return Response
* @throws BusinessException|Throwable
*/
public function view(Request $request): Response
{
$table = $request->get('table');
$table = Util::filterAlphaNum($table);
$form = Layui::buildForm($table, 'search');
$table_info = Util::getSchema($table, 'table');
$primary_key = $table_info['primary_key'][0] ?? null;
return raw_view("table/view", [
'form' => $form,
'table' => $table,
'primary_key' => $primary_key,
]);
}
/**
* 查询表
* @param Request $request
* @return Response
* @throws BusinessException
*/
public function show(Request $request): Response
{
$table_name = $request->get('table_name','');
$limit = (int)$request->get('limit', 10);
$page = (int)$request->get('page', 1);
$offset = ($page - 1) * $limit;
$database = config('database.connections')['plugin.admin.mysql']['database'];
$field = $request->get('field', 'TABLE_NAME');
$field = Util::filterAlphaNum($field);
$order = $request->get('order', 'asc');
$allow_column = ['TABLE_NAME', 'TABLE_COMMENT', 'ENGINE', 'TABLE_ROWS', 'CREATE_TIME', 'UPDATE_TIME', 'TABLE_COLLATION'];
if (!in_array($field, $allow_column)) {
$field = 'TABLE_NAME';
}
$order = $order === 'asc' ? 'asc' : 'desc';
$total = Util::db()->select("SELECT count(*)total FROM information_schema.`TABLES` WHERE TABLE_SCHEMA='$database' AND TABLE_NAME like '%{$table_name}%'")[0]->total ?? 0;
$tables = Util::db()->select("SELECT TABLE_NAME,TABLE_COMMENT,ENGINE,TABLE_ROWS,CREATE_TIME,UPDATE_TIME,TABLE_COLLATION FROM information_schema.`TABLES` WHERE TABLE_SCHEMA='$database' AND TABLE_NAME like '%{$table_name}%' order by $field $order limit $offset,$limit");
if ($tables) {
$table_names = array_column($tables, 'TABLE_NAME');
$table_rows_count = [];
foreach ($table_names as $table_name) {
$table_rows_count[$table_name] = Util::db()->table($table_name)->count();
}
foreach ($tables as $key => $table) {
$tables[$key]->TABLE_ROWS = $table_rows_count[$table->TABLE_NAME] ?? $table->TABLE_ROWS;
}
}
return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $tables]);
}
/**
* 创建表
* @param Request $request
* @return Response
* @throws BusinessException|Throwable
*/
public function create(Request $request): Response
{
if ($request->method() === 'GET') {
return raw_view("table/create", []);
}
$data = $request->post();
$table_name = Util::filterAlphaNum($data['table']);
$table_comment = Util::pdoQuote($data['table_comment']);
$columns = $data['columns'];
$forms = $data['forms'];
$keys = $data['keys'];
$primary_key_count = 0;
foreach ($columns as $index => $item) {
$columns[$index]['field'] = trim($item['field']);
if (!$item['field']) {
unset($columns[$index]);
continue;
}
$columns[$index]['primary_key'] = !empty($item['primary_key']);
if ($columns[$index]['primary_key']) {
$primary_key_count++;
}
$columns[$index]['auto_increment'] = !empty($item['auto_increment']);
$columns[$index]['nullable'] = !empty($item['nullable']);
if ($item['default'] === '') {
$columns[$index]['default'] = null;
} else if ($item['default'] === "''") {
$columns[$index]['default'] = '';
}
}
if ($primary_key_count > 1) {
throw new BusinessException('不支持复合主键');
}
foreach ($forms as $index => $item) {
if (!$item['field']) {
unset($forms[$index]);
continue;
}
$forms[$index]['form_show'] = !empty($item['form_show']);
$forms[$index]['list_show'] = !empty($item['list_show']);
$forms[$index]['enable_sort'] = !empty($item['enable_sort']);
$forms[$index]['searchable'] = !empty($item['searchable']);
}
foreach ($keys as $index => $item) {
if (!$item['name'] || !$item['columns']) {
unset($keys[$index]);
}
}
Util::schema()->create($table_name, function (Blueprint $table) use ($columns) {
$type_method_map = Util::methodControlMap();
foreach ($columns as $column) {
if (!isset($column['type'])) {
throw new BusinessException("请为{$column['field']}选择类型");
}
if (!isset($type_method_map[$column['type']])) {
throw new BusinessException("不支持的类型{$column['type']}");
}
$this->createColumn($column, $table);
}
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_general_ci';
$table->engine = 'InnoDB';
});
Util::db()->statement("ALTER TABLE `$table_name` COMMENT $table_comment");
// 索引
Util::schema()->table($table_name, function (Blueprint $table) use ($keys) {
foreach ($keys as $key) {
$name = $key['name'];
$columns = is_array($key['columns']) ? $key['columns'] : explode(',', $key['columns']);
$type = $key['type'];
if ($type == 'unique') {
$table->unique($columns, $name);
continue;
}
$table->index($columns, $name);
}
});
$form_schema_map = [];
foreach ($forms as $item) {
$form_schema_map[$item['field']] = $item;
}
$form_schema_map = json_encode($form_schema_map, JSON_UNESCAPED_UNICODE);
$this->updateSchemaOption($table_name, $form_schema_map);
return $this->json(0, 'ok');
}
/**
* 修改表
* @param Request $request
* @return Response
* @throws BusinessException|Throwable
*/
public function modify(Request $request): Response
{
if ($request->method() === 'GET') {
return raw_view("table/modify", ['table' => $request->get('table')]);
}
$data = $request->post();
$old_table_name = Util::filterAlphaNum($data['old_table']);
$table_name = Util::filterAlphaNum($data['table']);
$table_comment = $data['table_comment'];
$columns = $data['columns'];
$forms = $data['forms'];
$keys = $data['keys'];
$primary_key = null;
$auto_increment_column = null;
$schema = Util::getSchema($old_table_name);
$old_columns = $schema['columns'];
$old_primary_key = $schema['table']['primary_key'][0] ?? null;
$primary_key_count = $auto_increment_count = 0;
foreach ($columns as $index => $item) {
$columns[$index]['field'] = trim($item['field']);
if (!$item['field']) {
unset($columns[$index]);
continue;
}
$field = $item['field'];
$columns[$index]['auto_increment'] = !empty($item['auto_increment']);
$columns[$index]['nullable'] = !empty($item['nullable']);
$columns[$index]['primary_key'] = !empty($item['primary_key']);
if ($columns[$index]['primary_key']) {
$primary_key = $item['field'];
$columns[$index]['nullable'] = false;
$primary_key_count++;
}
if ($item['default'] === '') {
$columns[$index]['default'] = null;
} else if ($item['default'] === "''") {
$columns[$index]['default'] = '';
}
if ($columns[$index]['auto_increment']) {
$auto_increment_count++;
if (!isset($old_columns[$field]) || !$old_columns[$field]['auto_increment']) {
$auto_increment_column = $columns[$index];
unset($auto_increment_column['old_field']);
$columns[$index]['auto_increment'] = false;
}
}
}
if ($primary_key_count > 1) {
throw new BusinessException('不支持复合主键');
}
if ($auto_increment_count > 1) {
throw new BusinessException('一个表只能有一个自增字段,并且必须为key');
}
foreach ($forms as $index => $item) {
if (!$item['field']) {
unset($forms[$index]);
continue;
}
$forms[$index]['form_show'] = !empty($item['form_show']);
$forms[$index]['list_show'] = !empty($item['list_show']);
$forms[$index]['enable_sort'] = !empty($item['enable_sort']);
$forms[$index]['searchable'] = !empty($item['searchable']);
}
foreach ($keys as $index => $item) {
if (!$item['name'] || !$item['columns']) {
unset($keys[$index]);
}
}
// 改表名
if ($table_name != $old_table_name) {
Util::schema()->rename($old_table_name, $table_name);
}
$type_method_map = Util::methodControlMap();
foreach ($columns as $column) {
if (!isset($type_method_map[$column['type']])) {
throw new BusinessException("不支持的类型{$column['type']}");
}
$field = $column['old_field'] ?? $column['field'] ;
$old_column = $old_columns[$field] ?? [];
// 类型更改
foreach ($old_column as $key => $value) {
if (key_exists($key, $column) && ($column[$key] != $value || ($key === 'default' && $column[$key] !== $value))) {
$this->modifyColumn($column, $table_name);
break;
}
}
}
$table = Util::getSchema($table_name, 'table');
if ($table_comment !== $table['comment']) {
$table_comment = Util::pdoQuote($table_comment);
Util::db()->statement("ALTER TABLE `$table_name` COMMENT $table_comment");
}
$old_columns = Util::getSchema($table_name, 'columns');
Util::schema()->table($table_name, function (Blueprint $table) use ($columns, $old_columns, $keys, $table_name) {
foreach ($columns as $column) {
$field = $column['field'];
// 新字段
if (!isset($old_columns[$field])) {
$this->createColumn($column, $table);
}
}
// 更新索引名字
foreach ($keys as $key) {
if (!empty($key['old_name']) && $key['old_name'] !== $key['name']) {
$table->renameIndex($key['old_name'], $key['name']);
}
}
});
// 找到删除的字段
$old_columns = Util::getSchema($table_name, 'columns');
$exists_column_names = array_column($columns, 'field', 'field');
$old_columns_names = array_column($old_columns, 'field');
$drop_column_names = array_diff($old_columns_names, $exists_column_names);
$drop_column_names = Util::filterAlphaNum($drop_column_names);
foreach ($drop_column_names as $drop_column_name) {
Util::db()->statement("ALTER TABLE $table_name DROP COLUMN `$drop_column_name`");
}
$old_keys = Util::getSchema($table_name, 'keys');
Util::schema()->table($table_name, function (Blueprint $table) use ($keys, $old_keys, $table_name) {
foreach ($keys as $key) {
$key_name = $key['name'];
$old_key = $old_keys[$key_name] ?? [];
// 如果索引有变动,则删除索引,重新建立索引
if ($old_key && ($key['type'] != $old_key['type'] || $key['columns'] != implode(',', $old_key['columns']))) {
$old_key = [];
unset($old_keys[$key_name]);
echo "Drop Index $key_name\n";
$table->dropIndex($key_name);
}
// 重新建立索引
if (!$old_key) {
$name = $key['name'];
$columns = is_array($key['columns']) ? $key['columns'] : explode(',', $key['columns']);
$type = $key['type'];
if ($type == 'unique') {
$table->unique($columns, $name);
continue;
}
echo "Create Index $key_name\n";
$table->index($columns, $name);
}
}
// 找到删除的索引
$exists_key_names = array_column($keys, 'name', 'name');
$old_keys_names = array_column($old_keys, 'name');
$drop_keys_names = array_diff($old_keys_names, $exists_key_names);
foreach ($drop_keys_names as $name) {
echo "Drop Index $name\n";
$table->dropIndex($name);
}
});
// 变更主键
if ($old_primary_key != $primary_key) {
if ($old_primary_key) {
Util::db()->statement("ALTER TABLE `$table_name` DROP PRIMARY KEY");
}
if ($primary_key) {
$primary_key = Util::filterAlphaNum($primary_key);
Util::db()->statement("ALTER TABLE `$table_name` ADD PRIMARY KEY(`$primary_key`)");
}
}
// 一个表只能有一个 auto_increment 字段,并且是key,所以需要在最后设置
if ($auto_increment_column) {
$this->modifyColumn($auto_increment_column, $table_name);
}
$form_schema_map = [];
foreach ($forms as $item) {
$form_schema_map[$item['field']] = $item;
}
$form_schema_map = json_encode($form_schema_map, JSON_UNESCAPED_UNICODE);
$option_name = $this->updateSchemaOption($table_name, $form_schema_map);
return $this->json(0,$option_name);
}
/**
* 一键菜单
* @param Request $request
* @return Response
* @throws BusinessException|Throwable
*/
public function crud(Request $request): Response
{
$table_name = $request->input('table');
Util::checkTableName($table_name);
$prefix = 'wa_';
$table_basename = strpos($table_name, $prefix) === 0 ? substr($table_name, strlen($prefix)) : $table_name;
$inflector = InflectorFactory::create()->build();
$model_class = $inflector->classify($inflector->singularize($table_basename));
$base_path = '/plugin/admin/app';
if ($request->method() === 'GET') {
return raw_view("table/crud", [
'table' => $table_name,
'model' => "$base_path/model/$model_class.php",
'controller' => "$base_path/controller/{$model_class}Controller.php",
]);
}
$title = $request->post('title');
$pid = $request->post('pid', 0);
$icon = $request->post('icon', '');
$controller_file = '/' . trim($request->post('controller', ''), '/');
$model_file = '/' . trim($request->post('model', ''), '/');
$overwrite = $request->post('overwrite');
$ismodel = $request->post('ismodel');
if ($controller_file === '/' || $model_file === '/') {
return $this->json(1, '控制器和model不能为空');
}
$controller_info = pathinfo($controller_file);
$model_info = pathinfo($model_file);
$controller_path = Util::filterPath($controller_info['dirname'] ?? '');
$model_path = Util::filterPath($model_info['dirname'] ?? '');
$controller_file_name = Util::filterAlphaNum($controller_info['filename'] ?? '');
$model_file_name = Util::filterAlphaNum($model_info['filename'] ?? '');
if ($controller_info['extension'] !== 'php' || $model_info['extension'] !== 'php' ) {
return $this->json(1, '控制器和model必须以.php为后缀');
}
$pid = (int)$pid;
if ($pid) {
$parent_menu = Rule::find($pid);
if (!$parent_menu) {
return $this->json(1, '父菜单不存在');
}
}
if (!$overwrite) {
if (!$ismodel && is_file(base_path($controller_file))) {
return $this->json(1, "$controller_file 已经存在");
}
if (is_file(base_path($model_file))) {
return $this->json(1, "$model_file 已经存在");
}
}
$explode = explode('/', trim($controller_path, '/'));
$plugin = '';
if (strpos(strtolower($controller_file), '/controller/') === false) {
return $this->json(2, '控制器必须在controller目录下');
}
if ($explode[0] === 'plugin') {
if (count($explode) < 4) {
return $this->json(2, '控制器参数非法');
}
$plugin = $explode[1];
if (strtolower($explode[2]) !== 'app') {
return $this->json(2, '控制器必须在app目录');
}
$app = strtolower($explode[3]) !== 'controller' ? $explode[3] : '';
} else {
if (count($explode) < 2) {
return $this->json(3, '控制器参数非法');
}
if (strtolower($explode[0]) !== 'app') {
return $this->json(3, '控制器必须在app目录');
}
$app = strtolower($explode[1]) !== 'controller' ? $explode[1] : '';
}
Util::pauseFileMonitor();
try {
$model_class = $model_file_name;
$model_namespace = str_replace('/', '\\', trim($model_path, '/'));
// 创建model
$this->createModel($model_class, $model_namespace, base_path($model_file), $table_name);
// 仅生成模型
if($ismodel){
Util::resumeFileMonitor();
return $this->json(0);
}
$controller_suffix = $plugin ? config("plugin.$plugin.app.controller_suffix") : config('app.controller_suffix');
$controller_class = $controller_file_name;
$controller_namespace = str_replace('/', '\\', trim($controller_path, '/'));
// 创建controller
$controller_url_name = $controller_suffix && substr($controller_class, -strlen($controller_suffix)) === $controller_suffix ? substr($controller_class, 0, -strlen($controller_suffix)) : $controller_class;
$controller_url_name = str_replace('_', '-', $inflector->tableize($controller_url_name));
if ($plugin) {
array_splice($explode, 0, 2);
}
array_shift($explode);
if ($app) {
array_shift($explode);
}
foreach ($explode as $index => $item) {
if (strtolower($item) === 'controller') {
unset($explode[$index]);
}
}
$controller_base = implode('/', $explode);
$controller_class_with_namespace = "$controller_namespace\\$controller_class";
$template_path = $controller_base ? "$controller_base/$controller_url_name" : $controller_url_name;
$this->createController($controller_class, $controller_namespace, base_path($controller_file), $model_class, $model_namespace, $title, $template_path);
// 创建模版
$template_file_path = ($plugin ? "/plugin/$plugin" : '') . '/app/' . ($app ? "$app/" : '') . 'view/' . $template_path;
$model_class_with_namespace = "$model_namespace\\$model_class";
$primary_key = (new $model_class_with_namespace)->getKeyName();
$url_path_base = ($plugin ? "/app/$plugin/" : '/') . ($app ? "$app/" : '') . $template_path;
Util::$curdIsSort = true;// 后续查询均使用排序
$this->createTemplate(base_path($template_file_path), $table_name, $url_path_base, $primary_key, "$controller_namespace\\$controller_class");
Util::$curdIsSort = false;// 关闭 防止静态类不会销毁产生的错误
} finally {
Util::resumeFileMonitor();
}
$menu = Rule::where('key', $controller_class_with_namespace)->first();
if (!$menu) {
$menu = new Rule;
}
$menu->pid = $pid;
$menu->key = $controller_class_with_namespace;
$menu->title = $title;
$menu->icon = $icon;
$menu->href = "$url_path_base/index";
$menu->save();
$roles = admin('roles');
$rules = Role::whereIn('id', $roles)->pluck('rules');
$rule_ids = [];
foreach ($rules as $rule_string) {
if (!$rule_string) {
continue;
}
$rule_ids = array_merge($rule_ids, explode(',', $rule_string));
}
// 不是超级管理员,则需要给当前管理员这个菜单的权限
if (!in_array('*', $rule_ids) && $roles){
$role = Role::find(current($roles));
if ($role) {
$role->rules .= ",{$menu->id}";
}
$role->save();
}
return $this->json(0);
}
/**
* 创建model
* @param $class
* @param $namespace
* @param $file
* @param $table
* @return void
*/
protected function createModel($class, $namespace, $file, $table)
{
$this->mkdir($file);
$table_val = "'$table'";
$pk = 'id';
$properties = '';
$timestamps = '';
$incrementing = '';
$columns = [];
try {
$database = config('database.connections')['plugin.admin.mysql']['database'];
//plugin.admin.mysql
foreach (Util::db()->select("select COLUMN_NAME,DATA_TYPE,COLUMN_KEY,COLUMN_COMMENT from INFORMATION_SCHEMA.COLUMNS where table_name = '$table' and table_schema = '$database' order by ORDINAL_POSITION") as $item) {
if ($item->COLUMN_KEY === 'PRI') {
$pk = $item->COLUMN_NAME;
$item->COLUMN_COMMENT .= "(主键)";
if (strpos(strtolower($item->DATA_TYPE), 'int') === false) {
$incrementing = <<<EOF
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public \$incrementing = false;
EOF;
;
}
}
$type = $this->getType($item->DATA_TYPE);
$properties .= " * @property $type \${$item->COLUMN_NAME} {$item->COLUMN_COMMENT}\n";
$columns[$item->COLUMN_NAME] = $item->COLUMN_NAME;
}
} catch (Throwable $e) {echo $e;}
if (!isset($columns['created_at']) || !isset($columns['updated_at'])) {
$timestamps = <<<EOF
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public \$timestamps = false;
EOF;
}
$properties = rtrim($properties) ?: ' *';
$model_content = <<<EOF
<?php
namespace $namespace;
use plugin\admin\app\model\Base;
/**
$properties
*/
class $class extends Base
{
/**
* The table associated with the model.
*
* @var string
*/
protected \$table = $table_val;
/**
* The primary key associated with the table.
*
* @var string
*/
protected \$primaryKey = '$pk';
$timestamps
$incrementing
}
EOF;
file_put_contents($file, $model_content);
}
/**
* 创建控制器
* @param $controller_class
* @param $namespace
* @param $file
* @param $model_class
* @param $model_namespace
* @param $name
* @param $template_path
* @return void
*/
protected function createController($controller_class, $namespace, $file, $model_class, $model_namespace, $name, $template_path)
{
$model_class_alias = $model_class;
if (strtolower($model_class) === strtolower($controller_class)) {
$model_class_alias = "$model_class as {$model_class}Model";
$model_class = "{$model_class}Model";
}
$this->mkdir($file);
$controller_content = <<<EOF
<?php
namespace $namespace;
use support\Request;
use support\Response;
use $model_namespace\\$model_class_alias;
use plugin\admin\app\controller\Crud;
use support\\exception\BusinessException;
/**
* $name
*/
class $controller_class extends Crud
{
/**
* @var $model_class
*/
protected \$model = null;
/**
* 构造函数
* @return void
*/
public function __construct()
{
\$this->model = new $model_class;
}
/**
* 浏览
* @return Response
*/
public function index(): Response
{
return view('$template_path/index');
}
/**
* 插入
* @param Request \$request
* @return Response
* @throws BusinessException
*/
public function insert(Request \$request): Response
{
if (\$request->method() === 'POST') {
return parent::insert(\$request);
}
return view('$template_path/insert');
}
/**
* 更新
* @param Request \$request
* @return Response
* @throws BusinessException
*/
public function update(Request \$request): Response
{
if (\$request->method() === 'POST') {
return parent::update(\$request);
}
return view('$template_path/update');
}
}
EOF;
file_put_contents($file, $controller_content);
}
/**
* 创建控制器
* @param $template_file_path
* @param $table
* @param $template_path
* @param $url_path_base
* @param $primary_key
* @param $controller_class_with_namespace
* @return void
*/
protected function createTemplate($template_file_path, $table, $url_path_base, $primary_key, $controller_class_with_namespace)
{
$this->mkdir($template_file_path . '/index.html');
$code_base = Util::controllerToUrlPath($controller_class_with_namespace);
$code_base = str_replace('/', '.', trim($code_base, '/'));
$form = Layui::buildForm($table, 'search');
$html = $form->html(3);
$html = $html ? <<<EOF
<div class="layui-card">
<div class="layui-card-body">
<form class="layui-form top-search-from">
$html
<div class="layui-form-item layui-inline">
<label class="layui-form-label"></label>
<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
<i class="layui-icon layui-icon-search"></i>查询
</button>
<button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
<i class="layui-icon layui-icon-refresh"></i>重置
</button>
</div>
<div class="toggle-btn">
<a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
<a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
</div>
</form>
</div>
</div>
EOF
: '';
$html = str_replace("\n", "\n" . str_repeat(' ', 2), $html);
$js = $form->js(3);
$table_js = Layui::buildTable($table, 4);
$template_content = <<<EOF
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>浏览页面</title>
<link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
<link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
</head>
<body class="pear-container">
<!-- 顶部查询表单 -->
$html
<!-- 数据表格 -->
<div class="layui-card">
<div class="layui-card-body">
<table id="data-table" lay-filter="data-table"></table>
</div>
</div>
<!-- 表格顶部工具栏 -->
<script type="text/html" id="table-toolbar">
<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="$code_base.insert">
<i class="layui-icon layui-icon-add-1"></i>新增
</button>
<button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="$code_base.delete">
<i class="layui-icon layui-icon-delete"></i>删除
</button>
</script>
<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
<button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="$code_base.update">编辑</button>
<button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="$code_base.delete">删除</button>
</script>
<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/common.js"></script>
<script>
// 相关常量
const PRIMARY_KEY = "$primary_key";
const SELECT_API = "$url_path_base/select";
const UPDATE_API = "$url_path_base/update";
const DELETE_API = "$url_path_base/delete";
const INSERT_URL = "$url_path_base/insert";
const UPDATE_URL = "$url_path_base/update";
$js
// 表格渲染
layui.use(["table", "form", "common", "popup", "util"], function() {
let table = layui.table;
let form = layui.form;
let $ = layui.$;
let common = layui.common;
let util = layui.util;
$table_js
// 编辑或删除行事件
table.on("tool(data-table)", function(obj) {
if (obj.event === "remove") {
remove(obj);
} else if (obj.event === "edit") {
edit(obj);
}
});
// 表格顶部工具栏事件
table.on("toolbar(data-table)", function(obj) {
if (obj.event === "add") {
add();
} else if (obj.event === "refresh") {
refreshTable();
} else if (obj.event === "batchRemove") {
batchRemove(obj);
}
});
// 表格顶部搜索事件
form.on("submit(table-query)", function(data) {
table.reload("data-table", {
page: {
curr: 1
},
where: data.field
})
return false;
});
// 表格顶部搜索重置事件
form.on("submit(table-reset)", function(data) {
table.reload("data-table", {
where: []
})
});
// 字段允许为空
form.verify({
phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
number: [/(^$)|^\d+$/,'只能填写数字'],
date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
});
// 表格排序事件
table.on("sort(data-table)", function(obj){
table.reload("data-table", {
initSort: obj,
scrollPos: "fixed",
where: {
field: obj.field,
order: obj.type
}
});
});
// 表格新增数据
let add = function() {
layer.open({
type: 2,
title: "新增",
shade: 0.1,
maxmin: true,
area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
content: INSERT_URL
});
}
// 表格编辑数据
let edit = function(obj) {
let value = obj.data[PRIMARY_KEY];
layer.open({
type: 2,
title: "修改",
shade: 0.1,
maxmin: true,
area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
});
}
// 删除一行
let remove = function(obj) {
return doRemove(obj.data[PRIMARY_KEY]);
}
// 删除多行
let batchRemove = function(obj) {
let checkIds = common.checkField(obj, PRIMARY_KEY);
if (checkIds === "") {
layui.popup.warning("未选中数据");
return false;
}
doRemove(checkIds.split(","));
}
// 执行删除
let doRemove = function (ids) {
let data = {};
data[PRIMARY_KEY] = ids;
layer.confirm("确定删除?", {
icon: 3,
title: "提示"
}, function(index) {
layer.close(index);
let loading = layer.load();
$.ajax({
url: DELETE_API,
data: data,
dataType: "json",
type: "post",
success: function(res) {
layer.close(loading);
if (res.code) {
return layui.popup.failure(res.msg);
}
return layui.popup.success("操作成功", refreshTable);
}
})
});
}
// 刷新表格数据
window.refreshTable = function() {
table.reloadData("data-table", {
scrollPos: "fixed",
done: function (res, curr) {
if (curr > 1 && res.data && !res.data.length) {
curr = curr - 1;
table.reloadData("data-table", {
page: {
curr: curr
},
})
}
}
});
}
})
</script>
</body>
</html>
EOF;
file_put_contents("$template_file_path/index.html", $template_content);
$form = Layui::buildForm($table);