正在显示
46 个修改的文件
包含
4400 行增加
和
0 行删除
.bowerrc
0 → 100644
.env.sample
0 → 100644
.gitignore
0 → 100644
LICENSE
0 → 100644
1 | +Apache License | ||
2 | +Version 2.0, January 2004 | ||
3 | +http://www.apache.org/licenses/ | ||
4 | + | ||
5 | +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | ||
6 | + | ||
7 | +1. Definitions. | ||
8 | + | ||
9 | +"License" shall mean the terms and conditions for use, reproduction, and | ||
10 | +distribution as defined by Sections 1 through 9 of this document. | ||
11 | + | ||
12 | +"Licensor" shall mean the copyright owner or entity authorized by the copyright | ||
13 | +owner that is granting the License. | ||
14 | + | ||
15 | +"Legal Entity" shall mean the union of the acting entity and all other entities | ||
16 | +that control, are controlled by, or are under common control with that entity. | ||
17 | +For the purposes of this definition, "control" means (i) the power, direct or | ||
18 | +indirect, to cause the direction or management of such entity, whether by | ||
19 | +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the | ||
20 | +outstanding shares, or (iii) beneficial ownership of such entity. | ||
21 | + | ||
22 | +"You" (or "Your") shall mean an individual or Legal Entity exercising | ||
23 | +permissions granted by this License. | ||
24 | + | ||
25 | +"Source" form shall mean the preferred form for making modifications, including | ||
26 | +but not limited to software source code, documentation source, and configuration | ||
27 | +files. | ||
28 | + | ||
29 | +"Object" form shall mean any form resulting from mechanical transformation or | ||
30 | +translation of a Source form, including but not limited to compiled object code, | ||
31 | +generated documentation, and conversions to other media types. | ||
32 | + | ||
33 | +"Work" shall mean the work of authorship, whether in Source or Object form, made | ||
34 | +available under the License, as indicated by a copyright notice that is included | ||
35 | +in or attached to the work (an example is provided in the Appendix below). | ||
36 | + | ||
37 | +"Derivative Works" shall mean any work, whether in Source or Object form, that | ||
38 | +is based on (or derived from) the Work and for which the editorial revisions, | ||
39 | +annotations, elaborations, or other modifications represent, as a whole, an | ||
40 | +original work of authorship. For the purposes of this License, Derivative Works | ||
41 | +shall not include works that remain separable from, or merely link (or bind by | ||
42 | +name) to the interfaces of, the Work and Derivative Works thereof. | ||
43 | + | ||
44 | +"Contribution" shall mean any work of authorship, including the original version | ||
45 | +of the Work and any modifications or additions to that Work or Derivative Works | ||
46 | +thereof, that is intentionally submitted to Licensor for inclusion in the Work | ||
47 | +by the copyright owner or by an individual or Legal Entity authorized to submit | ||
48 | +on behalf of the copyright owner. For the purposes of this definition, | ||
49 | +"submitted" means any form of electronic, verbal, or written communication sent | ||
50 | +to the Licensor or its representatives, including but not limited to | ||
51 | +communication on electronic mailing lists, source code control systems, and | ||
52 | +issue tracking systems that are managed by, or on behalf of, the Licensor for | ||
53 | +the purpose of discussing and improving the Work, but excluding communication | ||
54 | +that is conspicuously marked or otherwise designated in writing by the copyright | ||
55 | +owner as "Not a Contribution." | ||
56 | + | ||
57 | +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf | ||
58 | +of whom a Contribution has been received by Licensor and subsequently | ||
59 | +incorporated within the Work. | ||
60 | + | ||
61 | +2. Grant of Copyright License. | ||
62 | + | ||
63 | +Subject to the terms and conditions of this License, each Contributor hereby | ||
64 | +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, | ||
65 | +irrevocable copyright license to reproduce, prepare Derivative Works of, | ||
66 | +publicly display, publicly perform, sublicense, and distribute the Work and such | ||
67 | +Derivative Works in Source or Object form. | ||
68 | + | ||
69 | +3. Grant of Patent License. | ||
70 | + | ||
71 | +Subject to the terms and conditions of this License, each Contributor hereby | ||
72 | +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, | ||
73 | +irrevocable (except as stated in this section) patent license to make, have | ||
74 | +made, use, offer to sell, sell, import, and otherwise transfer the Work, where | ||
75 | +such license applies only to those patent claims licensable by such Contributor | ||
76 | +that are necessarily infringed by their Contribution(s) alone or by combination | ||
77 | +of their Contribution(s) with the Work to which such Contribution(s) was | ||
78 | +submitted. If You institute patent litigation against any entity (including a | ||
79 | +cross-claim or counterclaim in a lawsuit) alleging that the Work or a | ||
80 | +Contribution incorporated within the Work constitutes direct or contributory | ||
81 | +patent infringement, then any patent licenses granted to You under this License | ||
82 | +for that Work shall terminate as of the date such litigation is filed. | ||
83 | + | ||
84 | +4. Redistribution. | ||
85 | + | ||
86 | +You may reproduce and distribute copies of the Work or Derivative Works thereof | ||
87 | +in any medium, with or without modifications, and in Source or Object form, | ||
88 | +provided that You meet the following conditions: | ||
89 | + | ||
90 | +You must give any other recipients of the Work or Derivative Works a copy of | ||
91 | +this License; and | ||
92 | +You must cause any modified files to carry prominent notices stating that You | ||
93 | +changed the files; and | ||
94 | +You must retain, in the Source form of any Derivative Works that You distribute, | ||
95 | +all copyright, patent, trademark, and attribution notices from the Source form | ||
96 | +of the Work, excluding those notices that do not pertain to any part of the | ||
97 | +Derivative Works; and | ||
98 | +If the Work includes a "NOTICE" text file as part of its distribution, then any | ||
99 | +Derivative Works that You distribute must include a readable copy of the | ||
100 | +attribution notices contained within such NOTICE file, excluding those notices | ||
101 | +that do not pertain to any part of the Derivative Works, in at least one of the | ||
102 | +following places: within a NOTICE text file distributed as part of the | ||
103 | +Derivative Works; within the Source form or documentation, if provided along | ||
104 | +with the Derivative Works; or, within a display generated by the Derivative | ||
105 | +Works, if and wherever such third-party notices normally appear. The contents of | ||
106 | +the NOTICE file are for informational purposes only and do not modify the | ||
107 | +License. You may add Your own attribution notices within Derivative Works that | ||
108 | +You distribute, alongside or as an addendum to the NOTICE text from the Work, | ||
109 | +provided that such additional attribution notices cannot be construed as | ||
110 | +modifying the License. | ||
111 | +You may add Your own copyright statement to Your modifications and may provide | ||
112 | +additional or different license terms and conditions for use, reproduction, or | ||
113 | +distribution of Your modifications, or for any such Derivative Works as a whole, | ||
114 | +provided Your use, reproduction, and distribution of the Work otherwise complies | ||
115 | +with the conditions stated in this License. | ||
116 | + | ||
117 | +5. Submission of Contributions. | ||
118 | + | ||
119 | +Unless You explicitly state otherwise, any Contribution intentionally submitted | ||
120 | +for inclusion in the Work by You to the Licensor shall be under the terms and | ||
121 | +conditions of this License, without any additional terms or conditions. | ||
122 | +Notwithstanding the above, nothing herein shall supersede or modify the terms of | ||
123 | +any separate license agreement you may have executed with Licensor regarding | ||
124 | +such Contributions. | ||
125 | + | ||
126 | +6. Trademarks. | ||
127 | + | ||
128 | +This License does not grant permission to use the trade names, trademarks, | ||
129 | +service marks, or product names of the Licensor, except as required for | ||
130 | +reasonable and customary use in describing the origin of the Work and | ||
131 | +reproducing the content of the NOTICE file. | ||
132 | + | ||
133 | +7. Disclaimer of Warranty. | ||
134 | + | ||
135 | +Unless required by applicable law or agreed to in writing, Licensor provides the | ||
136 | +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, | ||
137 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, | ||
138 | +including, without limitation, any warranties or conditions of TITLE, | ||
139 | +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are | ||
140 | +solely responsible for determining the appropriateness of using or | ||
141 | +redistributing the Work and assume any risks associated with Your exercise of | ||
142 | +permissions under this License. | ||
143 | + | ||
144 | +8. Limitation of Liability. | ||
145 | + | ||
146 | +In no event and under no legal theory, whether in tort (including negligence), | ||
147 | +contract, or otherwise, unless required by applicable law (such as deliberate | ||
148 | +and grossly negligent acts) or agreed to in writing, shall any Contributor be | ||
149 | +liable to You for damages, including any direct, indirect, special, incidental, | ||
150 | +or consequential damages of any character arising as a result of this License or | ||
151 | +out of the use or inability to use the Work (including but not limited to | ||
152 | +damages for loss of goodwill, work stoppage, computer failure or malfunction, or | ||
153 | +any and all other commercial damages or losses), even if such Contributor has | ||
154 | +been advised of the possibility of such damages. | ||
155 | + | ||
156 | +9. Accepting Warranty or Additional Liability. | ||
157 | + | ||
158 | +While redistributing the Work or Derivative Works thereof, You may choose to | ||
159 | +offer, and charge a fee for, acceptance of support, warranty, indemnity, or | ||
160 | +other liability obligations and/or rights consistent with this License. However, | ||
161 | +in accepting such obligations, You may act only on Your own behalf and on Your | ||
162 | +sole responsibility, not on behalf of any other Contributor, and only if You | ||
163 | +agree to indemnify, defend, and hold each Contributor harmless for any liability | ||
164 | +incurred by, or claims asserted against, such Contributor by reason of your | ||
165 | +accepting any such warranty or additional liability. | ||
166 | + | ||
167 | +END OF TERMS AND CONDITIONS | ||
168 | + | ||
169 | +APPENDIX: How to apply the Apache License to your work | ||
170 | + | ||
171 | +To apply the Apache License to your work, attach the following boilerplate | ||
172 | +notice, with the fields enclosed by brackets "{}" replaced with your own | ||
173 | +identifying information. (Don't include the brackets!) The text should be | ||
174 | +enclosed in the appropriate comment syntax for the file format. We also | ||
175 | +recommend that a file or class name and description of purpose be included on | ||
176 | +the same "printed page" as the copyright notice for easier identification within | ||
177 | +third-party archives. | ||
178 | + | ||
179 | + Copyright 2017 Karson | ||
180 | + | ||
181 | + Licensed under the Apache License, Version 2.0 (the "License"); | ||
182 | + you may not use this file except in compliance with the License. | ||
183 | + You may obtain a copy of the License at | ||
184 | + | ||
185 | + http://www.apache.org/licenses/LICENSE-2.0 | ||
186 | + | ||
187 | + Unless required by applicable law or agreed to in writing, software | ||
188 | + distributed under the License is distributed on an "AS IS" BASIS, | ||
189 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
190 | + See the License for the specific language governing permissions and | ||
191 | + limitations under the License. |
README.md
0 → 100644
1 | +FastAdmin是一款基于ThinkPHP5+Bootstrap的极速后台开发框架。 | ||
2 | + | ||
3 | + | ||
4 | +## **主要特性** | ||
5 | + | ||
6 | +* 基于`Auth`验证的权限管理系统 | ||
7 | + * 支持无限级父子级权限继承,父级的管理员可任意增删改子级管理员及权限设置 | ||
8 | + * 支持单管理员多角色 | ||
9 | + * 支持管理子级数据或个人数据 | ||
10 | +* 强大的一键生成功能 | ||
11 | + * 一键生成CRUD,包括控制器、模型、视图、JS、语言包、菜单、回收站等 | ||
12 | + * 一键压缩打包JS和CSS文件,一键CDN静态资源部署 | ||
13 | + * 一键生成控制器菜单和规则 | ||
14 | + * 一键生成API接口文档 | ||
15 | +* 完善的前端功能组件开发 | ||
16 | + * 基于`AdminLTE`二次开发 | ||
17 | + * 基于`Bootstrap`开发,自适应手机、平板、PC | ||
18 | + * 基于`RequireJS`进行JS模块管理,按需加载 | ||
19 | + * 基于`Less`进行样式开发 | ||
20 | + * 基于`Bower`进行前端组件包管理 | ||
21 | +* 强大的插件扩展功能,在线安装卸载升级插件 | ||
22 | +* 通用的会员模块和API模块 | ||
23 | +* 共用同一账号体系的Web端会员中心权限验证和API接口会员权限验证 | ||
24 | +* 二级域名部署支持,同时域名支持绑定到插件 | ||
25 | +* 多语言支持,服务端及客户端支持 | ||
26 | +* 强大的第三方模块支持([CMS](https://www.fastadmin.net/store/cms.html)、[博客](https://www.fastadmin.net/store/blog.html)、[知识付费问答](https://www.fastadmin.net/store/ask.html)) | ||
27 | +* 整合第三方短信接口(阿里云、腾讯云短信) | ||
28 | +* 无缝整合第三方云存储(七牛、阿里云OSS、又拍云)功能 | ||
29 | +* 第三方富文本编辑器支持(Summernote、Kindeditor、百度编辑器) | ||
30 | +* 第三方登录(QQ、微信、微博)整合 | ||
31 | +* 第三方支付(微信、支付宝)无缝整合,微信支持PC端扫码支付 | ||
32 | +* 丰富的插件应用市场 | ||
33 | + | ||
34 | +## **安装使用** | ||
35 | + | ||
36 | +https://doc.fastadmin.net | ||
37 | + | ||
38 | +## **在线演示** | ||
39 | + | ||
40 | +https://demo.fastadmin.net | ||
41 | + | ||
42 | +用户名:admin | ||
43 | + | ||
44 | +密 码:123456 | ||
45 | + | ||
46 | +提 示:演示站数据无法进行修改,请下载源码安装体验全部功能 | ||
47 | + | ||
48 | +## **界面截图** | ||
49 | +![控制台](https://gitee.com/uploads/images/2017/0411/113717_e99ff3e7_10933.png "控制台") | ||
50 | + | ||
51 | +## **问题反馈** | ||
52 | + | ||
53 | +在使用中有任何问题,请使用以下联系方式联系我们 | ||
54 | + | ||
55 | +交流社区: https://forum.fastadmin.net | ||
56 | + | ||
57 | +QQ群: [636393962](https://jq.qq.com/?_wv=1027&k=487PNBb)(满) [708784003](https://jq.qq.com/?_wv=1027&k=5ObjtwM)(满) [964776039](https://jq.qq.com/?_wv=1027&k=59qjU2P)(3群) | ||
58 | + | ||
59 | +Email: (karsonzhang#163.com, 把#换成@) | ||
60 | + | ||
61 | +Github: https://github.com/karsonzhang/fastadmin | ||
62 | + | ||
63 | +Gitee: https://gitee.com/karson/fastadmin | ||
64 | + | ||
65 | +## **特别鸣谢** | ||
66 | + | ||
67 | +感谢以下的项目,排名不分先后 | ||
68 | + | ||
69 | +ThinkPHP:http://www.thinkphp.cn | ||
70 | + | ||
71 | +AdminLTE:https://adminlte.io | ||
72 | + | ||
73 | +Bootstrap:http://getbootstrap.com | ||
74 | + | ||
75 | +jQuery:http://jquery.com | ||
76 | + | ||
77 | +Bootstrap-table:https://github.com/wenzhixin/bootstrap-table | ||
78 | + | ||
79 | +Nice-validator: https://validator.niceue.com | ||
80 | + | ||
81 | +SelectPage: https://github.com/TerryZ/SelectPage | ||
82 | + | ||
83 | + | ||
84 | +## **版权信息** | ||
85 | + | ||
86 | +FastAdmin遵循Apache2开源协议发布,并提供免费使用。 | ||
87 | + | ||
88 | +本项目包含的第三方源码和二进制文件之版权信息另行标注。 | ||
89 | + | ||
90 | +版权所有Copyright © 2017-2019 by FastAdmin (https://www.fastadmin.net) | ||
91 | + | ||
92 | +All rights reserved。 |
application/.htaccess
0 → 100644
1 | +deny from all |
application/admin/behavior/AdminLog.php
0 → 100644
application/admin/command/Addon.php
0 → 100644
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command; | ||
4 | + | ||
5 | +use think\addons\AddonException; | ||
6 | +use think\addons\Service; | ||
7 | +use think\Config; | ||
8 | +use think\console\Command; | ||
9 | +use think\console\Input; | ||
10 | +use think\console\input\Option; | ||
11 | +use think\console\Output; | ||
12 | +use think\Db; | ||
13 | +use think\Exception; | ||
14 | +use think\exception\PDOException; | ||
15 | + | ||
16 | +class Addon extends Command | ||
17 | +{ | ||
18 | + | ||
19 | + protected function configure() | ||
20 | + { | ||
21 | + $this | ||
22 | + ->setName('addon') | ||
23 | + ->addOption('name', 'a', Option::VALUE_REQUIRED, 'addon name', null) | ||
24 | + ->addOption('action', 'c', Option::VALUE_REQUIRED, 'action(create/enable/disable/install/uninstall/refresh/upgrade/package/move)', 'create') | ||
25 | + ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null) | ||
26 | + ->addOption('release', 'r', Option::VALUE_OPTIONAL, 'addon release version', null) | ||
27 | + ->addOption('uid', 'u', Option::VALUE_OPTIONAL, 'fastadmin uid', null) | ||
28 | + ->addOption('token', 't', Option::VALUE_OPTIONAL, 'fastadmin token', null) | ||
29 | + ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local package', null) | ||
30 | + ->setDescription('Addon manager'); | ||
31 | + } | ||
32 | + | ||
33 | + protected function execute(Input $input, Output $output) | ||
34 | + { | ||
35 | + $name = $input->getOption('name') ?: ''; | ||
36 | + $action = $input->getOption('action') ?: ''; | ||
37 | + if (stripos($name, 'addons/') !== false) { | ||
38 | + $name = explode('/', $name)[1]; | ||
39 | + } | ||
40 | + //强制覆盖 | ||
41 | + $force = $input->getOption('force'); | ||
42 | + //版本 | ||
43 | + $release = $input->getOption('release') ?: ''; | ||
44 | + //uid | ||
45 | + $uid = $input->getOption('uid') ?: ''; | ||
46 | + //token | ||
47 | + $token = $input->getOption('token') ?: ''; | ||
48 | + | ||
49 | + include dirname(__DIR__) . DS . 'common.php'; | ||
50 | + | ||
51 | + if (!$name) { | ||
52 | + throw new Exception('Addon name could not be empty'); | ||
53 | + } | ||
54 | + if (!$action || !in_array($action, ['create', 'disable', 'enable', 'install', 'uninstall', 'refresh', 'upgrade', 'package', 'move'])) { | ||
55 | + throw new Exception('Please input correct action name'); | ||
56 | + } | ||
57 | + | ||
58 | + // 查询一次SQL,判断连接是否正常 | ||
59 | + Db::execute("SELECT 1"); | ||
60 | + | ||
61 | + $addonDir = ADDON_PATH . $name . DS; | ||
62 | + switch ($action) { | ||
63 | + case 'create': | ||
64 | + //非覆盖模式时如果存在则报错 | ||
65 | + if (is_dir($addonDir) && !$force) { | ||
66 | + throw new Exception("addon already exists!\nIf you need to create again, use the parameter --force=true "); | ||
67 | + } | ||
68 | + //如果存在先移除 | ||
69 | + if (is_dir($addonDir)) { | ||
70 | + rmdirs($addonDir); | ||
71 | + } | ||
72 | + mkdir($addonDir, 0755, true); | ||
73 | + mkdir($addonDir . DS . 'controller', 0755, true); | ||
74 | + $menuList = \app\common\library\Menu::export($name); | ||
75 | + $createMenu = $this->getCreateMenu($menuList); | ||
76 | + $prefix = Config::get('database.prefix'); | ||
77 | + $createTableSql = ''; | ||
78 | + try { | ||
79 | + $result = Db::query("SHOW CREATE TABLE `" . $prefix . $name . "`;"); | ||
80 | + if (isset($result[0]) && isset($result[0]['Create Table'])) { | ||
81 | + $createTableSql = $result[0]['Create Table']; | ||
82 | + } | ||
83 | + } catch (PDOException $e) { | ||
84 | + | ||
85 | + } | ||
86 | + | ||
87 | + $data = [ | ||
88 | + 'name' => $name, | ||
89 | + 'addon' => $name, | ||
90 | + 'addonClassName' => ucfirst($name), | ||
91 | + 'addonInstallMenu' => $createMenu ? "\$menu = " . var_export_short($createMenu, "\t") . ";\n\tMenu::create(\$menu);" : '', | ||
92 | + 'addonUninstallMenu' => $menuList ? 'Menu::delete("' . $name . '");' : '', | ||
93 | + 'addonEnableMenu' => $menuList ? 'Menu::enable("' . $name . '");' : '', | ||
94 | + 'addonDisableMenu' => $menuList ? 'Menu::disable("' . $name . '");' : '', | ||
95 | + ]; | ||
96 | + $this->writeToFile("addon", $data, $addonDir . ucfirst($name) . '.php'); | ||
97 | + $this->writeToFile("config", $data, $addonDir . 'config.php'); | ||
98 | + $this->writeToFile("info", $data, $addonDir . 'info.ini'); | ||
99 | + $this->writeToFile("controller", $data, $addonDir . 'controller' . DS . 'Index.php'); | ||
100 | + if ($createTableSql) { | ||
101 | + $createTableSql = str_replace("`" . $prefix, '`__PREFIX__', $createTableSql); | ||
102 | + file_put_contents($addonDir . 'install.sql', $createTableSql); | ||
103 | + } | ||
104 | + | ||
105 | + $output->info("Create Successed!"); | ||
106 | + break; | ||
107 | + case 'disable': | ||
108 | + case 'enable': | ||
109 | + try { | ||
110 | + //调用启用、禁用的方法 | ||
111 | + Service::$action($name, 0); | ||
112 | + } catch (AddonException $e) { | ||
113 | + if ($e->getCode() != -3) { | ||
114 | + throw new Exception($e->getMessage()); | ||
115 | + } | ||
116 | + if (!$force) { | ||
117 | + //如果有冲突文件则提醒 | ||
118 | + $data = $e->getData(); | ||
119 | + foreach ($data['conflictlist'] as $k => $v) { | ||
120 | + $output->warning($v); | ||
121 | + } | ||
122 | + $output->info("Are you sure you want to " . ($action == 'enable' ? 'override' : 'delete') . " all those files? Type 'yes' to continue: "); | ||
123 | + $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r')); | ||
124 | + if (trim($line) != 'yes') { | ||
125 | + throw new Exception("Operation is aborted!"); | ||
126 | + } | ||
127 | + } | ||
128 | + //调用启用、禁用的方法 | ||
129 | + Service::$action($name, 1); | ||
130 | + } catch (Exception $e) { | ||
131 | + throw new Exception($e->getMessage()); | ||
132 | + } | ||
133 | + $output->info(ucfirst($action) . " Successed!"); | ||
134 | + break; | ||
135 | + case 'install': | ||
136 | + //非覆盖模式时如果存在则报错 | ||
137 | + if (is_dir($addonDir) && !$force) { | ||
138 | + throw new Exception("addon already exists!\nIf you need to install again, use the parameter --force=true "); | ||
139 | + } | ||
140 | + //如果存在先移除 | ||
141 | + if (is_dir($addonDir)) { | ||
142 | + rmdirs($addonDir); | ||
143 | + } | ||
144 | + // 获取本地路径 | ||
145 | + $local = $input->getOption('local'); | ||
146 | + try { | ||
147 | + Service::install($name, 0, ['version' => $release], $local); | ||
148 | + } catch (AddonException $e) { | ||
149 | + if ($e->getCode() != -3) { | ||
150 | + throw new Exception($e->getMessage()); | ||
151 | + } | ||
152 | + if (!$force) { | ||
153 | + //如果有冲突文件则提醒 | ||
154 | + $data = $e->getData(); | ||
155 | + foreach ($data['conflictlist'] as $k => $v) { | ||
156 | + $output->warning($v); | ||
157 | + } | ||
158 | + $output->info("Are you sure you want to override all those files? Type 'yes' to continue: "); | ||
159 | + $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r')); | ||
160 | + if (trim($line) != 'yes') { | ||
161 | + throw new Exception("Operation is aborted!"); | ||
162 | + } | ||
163 | + } | ||
164 | + Service::install($name, 1, ['version' => $release, 'uid' => $uid, 'token' => $token], $local); | ||
165 | + } catch (Exception $e) { | ||
166 | + throw new Exception($e->getMessage()); | ||
167 | + } | ||
168 | + | ||
169 | + $output->info("Install Successed!"); | ||
170 | + break; | ||
171 | + case 'uninstall': | ||
172 | + //非覆盖模式时如果存在则报错 | ||
173 | + if (!$force) { | ||
174 | + throw new Exception("If you need to uninstall addon, use the parameter --force=true "); | ||
175 | + } | ||
176 | + try { | ||
177 | + Service::uninstall($name, 0); | ||
178 | + } catch (AddonException $e) { | ||
179 | + if ($e->getCode() != -3) { | ||
180 | + throw new Exception($e->getMessage()); | ||
181 | + } | ||
182 | + if (!$force) { | ||
183 | + //如果有冲突文件则提醒 | ||
184 | + $data = $e->getData(); | ||
185 | + foreach ($data['conflictlist'] as $k => $v) { | ||
186 | + $output->warning($v); | ||
187 | + } | ||
188 | + $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: "); | ||
189 | + $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r')); | ||
190 | + if (trim($line) != 'yes') { | ||
191 | + throw new Exception("Operation is aborted!"); | ||
192 | + } | ||
193 | + } | ||
194 | + Service::uninstall($name, 1); | ||
195 | + } catch (Exception $e) { | ||
196 | + throw new Exception($e->getMessage()); | ||
197 | + } | ||
198 | + | ||
199 | + $output->info("Uninstall Successed!"); | ||
200 | + break; | ||
201 | + case 'refresh': | ||
202 | + Service::refresh(); | ||
203 | + $output->info("Refresh Successed!"); | ||
204 | + break; | ||
205 | + case 'upgrade': | ||
206 | + Service::upgrade($name, ['version' => $release, 'uid' => $uid, 'token' => $token]); | ||
207 | + $output->info("Upgrade Successed!"); | ||
208 | + break; | ||
209 | + case 'package': | ||
210 | + $infoFile = $addonDir . 'info.ini'; | ||
211 | + if (!is_file($infoFile)) { | ||
212 | + throw new Exception(__('Addon info file was not found')); | ||
213 | + } | ||
214 | + | ||
215 | + $info = get_addon_info($name); | ||
216 | + if (!$info) { | ||
217 | + throw new Exception(__('Addon info file data incorrect')); | ||
218 | + } | ||
219 | + $infoname = isset($info['name']) ? $info['name'] : ''; | ||
220 | + if (!$infoname || !preg_match("/^[a-z]+$/i", $infoname) || $infoname != $name) { | ||
221 | + throw new Exception(__('Addon info name incorrect')); | ||
222 | + } | ||
223 | + | ||
224 | + $infoversion = isset($info['version']) ? $info['version'] : ''; | ||
225 | + if (!$infoversion || !preg_match("/^\d+\.\d+\.\d+$/i", $infoversion)) { | ||
226 | + throw new Exception(__('Addon info version incorrect')); | ||
227 | + } | ||
228 | + | ||
229 | + $addonTmpDir = RUNTIME_PATH . 'addons' . DS; | ||
230 | + if (!is_dir($addonTmpDir)) { | ||
231 | + @mkdir($addonTmpDir, 0755, true); | ||
232 | + } | ||
233 | + $addonFile = $addonTmpDir . $infoname . '-' . $infoversion . '.zip'; | ||
234 | + if (!class_exists('ZipArchive')) { | ||
235 | + throw new Exception(__('ZinArchive not install')); | ||
236 | + } | ||
237 | + $zip = new \ZipArchive; | ||
238 | + $zip->open($addonFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); | ||
239 | + | ||
240 | + $files = new \RecursiveIteratorIterator( | ||
241 | + new \RecursiveDirectoryIterator($addonDir), \RecursiveIteratorIterator::LEAVES_ONLY | ||
242 | + ); | ||
243 | + | ||
244 | + foreach ($files as $name => $file) { | ||
245 | + if (!$file->isDir()) { | ||
246 | + $filePath = $file->getRealPath(); | ||
247 | + $relativePath = str_replace(DS, '/', substr($filePath, strlen($addonDir))); | ||
248 | + if (!in_array($file->getFilename(), ['.git', '.DS_Store', 'Thumbs.db'])) { | ||
249 | + $zip->addFile($filePath, $relativePath); | ||
250 | + } | ||
251 | + } | ||
252 | + } | ||
253 | + $zip->close(); | ||
254 | + $output->info("Package Successed!"); | ||
255 | + break; | ||
256 | + case 'move': | ||
257 | + $movePath = [ | ||
258 | + 'adminOnlySelfDir' => ['admin/behavior', 'admin/controller', 'admin/library', 'admin/model', 'admin/validate', 'admin/view'], | ||
259 | + 'adminAllSubDir' => ['admin/lang'], | ||
260 | + 'publicDir' => ['public/assets/addons', 'public/assets/js/backend'] | ||
261 | + ]; | ||
262 | + $paths = []; | ||
263 | + $appPath = str_replace('/', DS, APP_PATH); | ||
264 | + $rootPath = str_replace('/', DS, ROOT_PATH); | ||
265 | + foreach ($movePath as $k => $items) { | ||
266 | + switch ($k) { | ||
267 | + case 'adminOnlySelfDir': | ||
268 | + foreach ($items as $v) { | ||
269 | + $v = str_replace('/', DS, $v); | ||
270 | + $oldPath = $appPath . $v . DS . $name; | ||
271 | + $newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $name; | ||
272 | + $paths[$oldPath] = $newPath; | ||
273 | + } | ||
274 | + break; | ||
275 | + case 'adminAllSubDir': | ||
276 | + foreach ($items as $v) { | ||
277 | + $v = str_replace('/', DS, $v); | ||
278 | + $vPath = $appPath . $v; | ||
279 | + $list = scandir($vPath); | ||
280 | + foreach ($list as $_v) { | ||
281 | + if (!in_array($_v, ['.', '..']) && is_dir($vPath . DS . $_v)) { | ||
282 | + $oldPath = $appPath . $v . DS . $_v . DS . $name; | ||
283 | + $newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $_v . DS . $name; | ||
284 | + $paths[$oldPath] = $newPath; | ||
285 | + } | ||
286 | + } | ||
287 | + } | ||
288 | + break; | ||
289 | + case 'publicDir': | ||
290 | + foreach ($items as $v) { | ||
291 | + $v = str_replace('/', DS, $v); | ||
292 | + $oldPath = $rootPath . $v . DS . $name; | ||
293 | + $newPath = $rootPath . 'addons' . DS . $name . DS . $v . DS . $name; | ||
294 | + $paths[$oldPath] = $newPath; | ||
295 | + } | ||
296 | + break; | ||
297 | + } | ||
298 | + } | ||
299 | + foreach ($paths as $oldPath => $newPath) { | ||
300 | + if (is_dir($oldPath)) { | ||
301 | + if ($force) { | ||
302 | + if (is_dir($newPath)) { | ||
303 | + $list = scandir($newPath); | ||
304 | + foreach ($list as $_v) { | ||
305 | + if (!in_array($_v, ['.', '..'])) { | ||
306 | + $file = $newPath . DS . $_v; | ||
307 | + @chmod($file, 0777); | ||
308 | + @unlink($file); | ||
309 | + } | ||
310 | + } | ||
311 | + @rmdir($newPath); | ||
312 | + } | ||
313 | + } | ||
314 | + copydirs($oldPath, $newPath); | ||
315 | + } | ||
316 | + } | ||
317 | + break; | ||
318 | + default: | ||
319 | + break; | ||
320 | + } | ||
321 | + } | ||
322 | + | ||
323 | + /** | ||
324 | + * 获取创建菜单的数组 | ||
325 | + * @param array $menu | ||
326 | + * @return array | ||
327 | + */ | ||
328 | + protected function getCreateMenu($menu) | ||
329 | + { | ||
330 | + $result = []; | ||
331 | + foreach ($menu as $k => & $v) { | ||
332 | + $arr = [ | ||
333 | + 'name' => $v['name'], | ||
334 | + 'title' => $v['title'], | ||
335 | + ]; | ||
336 | + if ($v['icon'] != 'fa fa-circle-o') { | ||
337 | + $arr['icon'] = $v['icon']; | ||
338 | + } | ||
339 | + if ($v['ismenu']) { | ||
340 | + $arr['ismenu'] = $v['ismenu']; | ||
341 | + } | ||
342 | + if (isset($v['childlist']) && $v['childlist']) { | ||
343 | + $arr['sublist'] = $this->getCreateMenu($v['childlist']); | ||
344 | + } | ||
345 | + $result[] = $arr; | ||
346 | + } | ||
347 | + return $result; | ||
348 | + } | ||
349 | + | ||
350 | + /** | ||
351 | + * 写入到文件 | ||
352 | + * @param string $name | ||
353 | + * @param array $data | ||
354 | + * @param string $pathname | ||
355 | + * @return mixed | ||
356 | + */ | ||
357 | + protected function writeToFile($name, $data, $pathname) | ||
358 | + { | ||
359 | + $search = $replace = []; | ||
360 | + foreach ($data as $k => $v) { | ||
361 | + $search[] = "{%{$k}%}"; | ||
362 | + $replace[] = $v; | ||
363 | + } | ||
364 | + $stub = file_get_contents($this->getStub($name)); | ||
365 | + $content = str_replace($search, $replace, $stub); | ||
366 | + | ||
367 | + if (!is_dir(dirname($pathname))) { | ||
368 | + mkdir(strtolower(dirname($pathname)), 0755, true); | ||
369 | + } | ||
370 | + return file_put_contents($pathname, $content); | ||
371 | + } | ||
372 | + | ||
373 | + /** | ||
374 | + * 获取基础模板 | ||
375 | + * @param string $name | ||
376 | + * @return string | ||
377 | + */ | ||
378 | + protected function getStub($name) | ||
379 | + { | ||
380 | + return __DIR__ . '/Addon/stubs/' . $name . '.stub'; | ||
381 | + } | ||
382 | + | ||
383 | +} |
1 | +<?php | ||
2 | + | ||
3 | +namespace addons\{%name%}; | ||
4 | + | ||
5 | +use app\common\library\Menu; | ||
6 | +use think\Addons; | ||
7 | + | ||
8 | +/** | ||
9 | + * 插件 | ||
10 | + */ | ||
11 | +class {%addonClassName%} extends Addons | ||
12 | +{ | ||
13 | + | ||
14 | + /** | ||
15 | + * 插件安装方法 | ||
16 | + * @return bool | ||
17 | + */ | ||
18 | + public function install() | ||
19 | + { | ||
20 | + {%addonInstallMenu%} | ||
21 | + return true; | ||
22 | + } | ||
23 | + | ||
24 | + /** | ||
25 | + * 插件卸载方法 | ||
26 | + * @return bool | ||
27 | + */ | ||
28 | + public function uninstall() | ||
29 | + { | ||
30 | + {%addonUninstallMenu%} | ||
31 | + return true; | ||
32 | + } | ||
33 | + | ||
34 | + /** | ||
35 | + * 插件启用方法 | ||
36 | + * @return bool | ||
37 | + */ | ||
38 | + public function enable() | ||
39 | + { | ||
40 | + {%addonEnableMenu%} | ||
41 | + return true; | ||
42 | + } | ||
43 | + | ||
44 | + /** | ||
45 | + * 插件禁用方法 | ||
46 | + * @return bool | ||
47 | + */ | ||
48 | + public function disable() | ||
49 | + { | ||
50 | + {%addonDisableMenu%} | ||
51 | + return true; | ||
52 | + } | ||
53 | + | ||
54 | + /** | ||
55 | + * 实现钩子方法 | ||
56 | + * @return mixed | ||
57 | + */ | ||
58 | + public function testhook($param) | ||
59 | + { | ||
60 | + // 调用钩子时候的参数信息 | ||
61 | + print_r($param); | ||
62 | + // 当前插件的配置信息,配置信息存在当前目录的config.php文件中,见下方 | ||
63 | + print_r($this->getConfig()); | ||
64 | + // 可以返回模板,模板文件默认读取的为插件目录中的文件。模板名不能为空! | ||
65 | + //return $this->fetch('view/info'); | ||
66 | + } | ||
67 | + | ||
68 | +} |
1 | +<?php | ||
2 | + | ||
3 | +return [ | ||
4 | + [ | ||
5 | + //配置唯一标识 | ||
6 | + 'name' => 'usernmae', | ||
7 | + //显示的标题 | ||
8 | + 'title' => '用户名', | ||
9 | + //类型 | ||
10 | + 'type' => 'string', | ||
11 | + //数据字典 | ||
12 | + 'content' => [ | ||
13 | + ], | ||
14 | + //值 | ||
15 | + 'value' => '', | ||
16 | + //验证规则 | ||
17 | + 'rule' => 'required', | ||
18 | + //错误消息 | ||
19 | + 'msg' => '', | ||
20 | + //提示消息 | ||
21 | + 'tip' => '', | ||
22 | + //成功消息 | ||
23 | + 'ok' => '', | ||
24 | + //扩展信息 | ||
25 | + 'extend' => '' | ||
26 | + ], | ||
27 | + [ | ||
28 | + 'name' => 'password', | ||
29 | + 'title' => '密码', | ||
30 | + 'type' => 'string', | ||
31 | + 'content' => [ | ||
32 | + ], | ||
33 | + 'value' => '', | ||
34 | + 'rule' => 'required', | ||
35 | + 'msg' => '', | ||
36 | + 'tip' => '', | ||
37 | + 'ok' => '', | ||
38 | + 'extend' => '' | ||
39 | + ], | ||
40 | +]; |
application/admin/command/Api.php
0 → 100644
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command; | ||
4 | + | ||
5 | +use app\admin\command\Api\library\Builder; | ||
6 | +use think\Config; | ||
7 | +use think\console\Command; | ||
8 | +use think\console\Input; | ||
9 | +use think\console\input\Option; | ||
10 | +use think\console\Output; | ||
11 | +use think\Exception; | ||
12 | + | ||
13 | +class Api extends Command | ||
14 | +{ | ||
15 | + protected function configure() | ||
16 | + { | ||
17 | + $site = Config::get('site'); | ||
18 | + $this | ||
19 | + ->setName('api') | ||
20 | + ->addOption('url', 'u', Option::VALUE_OPTIONAL, 'default api url', '') | ||
21 | + ->addOption('module', 'm', Option::VALUE_OPTIONAL, 'module name(admin/index/api)', 'api') | ||
22 | + ->addOption('output', 'o', Option::VALUE_OPTIONAL, 'output index file name', 'api.html') | ||
23 | + ->addOption('template', 'e', Option::VALUE_OPTIONAL, '', 'index.html') | ||
24 | + ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override general file', false) | ||
25 | + ->addOption('title', 't', Option::VALUE_OPTIONAL, 'document title', $site['name']) | ||
26 | + ->addOption('author', 'a', Option::VALUE_OPTIONAL, 'document author', $site['name']) | ||
27 | + ->addOption('class', 'c', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'extend class', null) | ||
28 | + ->addOption('language', 'l', Option::VALUE_OPTIONAL, 'language', 'zh-cn') | ||
29 | + ->setDescription('Build Api document from controller'); | ||
30 | + } | ||
31 | + | ||
32 | + protected function execute(Input $input, Output $output) | ||
33 | + { | ||
34 | + $apiDir = __DIR__ . DS . 'Api' . DS; | ||
35 | + | ||
36 | + $force = $input->getOption('force'); | ||
37 | + $url = $input->getOption('url'); | ||
38 | + $language = $input->getOption('language'); | ||
39 | + $language = $language ? $language : 'zh-cn'; | ||
40 | + $langFile = $apiDir . 'lang' . DS . $language . '.php'; | ||
41 | + if (!is_file($langFile)) { | ||
42 | + throw new Exception('language file not found'); | ||
43 | + } | ||
44 | + $lang = include_once $langFile; | ||
45 | + // 目标目录 | ||
46 | + $output_dir = ROOT_PATH . 'public' . DS; | ||
47 | + $output_file = $output_dir . $input->getOption('output'); | ||
48 | + if (is_file($output_file) && !$force) { | ||
49 | + throw new Exception("api index file already exists!\nIf you need to rebuild again, use the parameter --force=true "); | ||
50 | + } | ||
51 | + // 模板文件 | ||
52 | + $template_dir = $apiDir . 'template' . DS; | ||
53 | + $template_file = $template_dir . $input->getOption('template'); | ||
54 | + if (!is_file($template_file)) { | ||
55 | + throw new Exception('template file not found'); | ||
56 | + } | ||
57 | + // 额外的类 | ||
58 | + $classes = $input->getOption('class'); | ||
59 | + // 标题 | ||
60 | + $title = $input->getOption('title'); | ||
61 | + // 作者 | ||
62 | + $author = $input->getOption('author'); | ||
63 | + // 模块 | ||
64 | + $module = $input->getOption('module'); | ||
65 | + | ||
66 | + $moduleDir = APP_PATH . $module . DS; | ||
67 | + if (!is_dir($moduleDir)) { | ||
68 | + throw new Exception('module not found'); | ||
69 | + } | ||
70 | + | ||
71 | + if (version_compare(PHP_VERSION, '7.0.0', '<')) { | ||
72 | + if (extension_loaded('Zend OPcache')) { | ||
73 | + $configuration = opcache_get_configuration(); | ||
74 | + $directives = $configuration['directives']; | ||
75 | + $configName = request()->isCli() ? 'opcache.enable_cli' : 'opcache.enable'; | ||
76 | + if (!$directives[$configName]) { | ||
77 | + throw new Exception("Please make sure {$configName} is turned on, Get help:https://forum.fastadmin.net/d/1321"); | ||
78 | + } | ||
79 | + } else { | ||
80 | + throw new Exception("Please make sure opcache already enabled, Get help:https://forum.fastadmin.net/d/1321"); | ||
81 | + } | ||
82 | + } | ||
83 | + | ||
84 | + $controllerDir = $moduleDir . Config::get('url_controller_layer') . DS; | ||
85 | + $files = new \RecursiveIteratorIterator( | ||
86 | + new \RecursiveDirectoryIterator($controllerDir), | ||
87 | + \RecursiveIteratorIterator::LEAVES_ONLY | ||
88 | + ); | ||
89 | + | ||
90 | + foreach ($files as $name => $file) { | ||
91 | + if (!$file->isDir() && $file->getExtension() == 'php') { | ||
92 | + $filePath = $file->getRealPath(); | ||
93 | + $classes[] = $this->get_class_from_file($filePath); | ||
94 | + } | ||
95 | + } | ||
96 | + $classes = array_unique(array_filter($classes)); | ||
97 | + | ||
98 | + $config = [ | ||
99 | + 'title' => $title, | ||
100 | + 'author' => $author, | ||
101 | + 'description' => '', | ||
102 | + 'apiurl' => $url, | ||
103 | + 'language' => $language, | ||
104 | + ]; | ||
105 | + $builder = new Builder($classes); | ||
106 | + $content = $builder->render($template_file, ['config' => $config, 'lang' => $lang]); | ||
107 | + | ||
108 | + if (!file_put_contents($output_file, $content)) { | ||
109 | + throw new Exception('Cannot save the content to ' . $output_file); | ||
110 | + } | ||
111 | + $output->info("Build Successed!"); | ||
112 | + } | ||
113 | + | ||
114 | + /** | ||
115 | + * get full qualified class name | ||
116 | + * | ||
117 | + * @param string $path_to_file | ||
118 | + * @author JBYRNE http://jarretbyrne.com/2015/06/197/ | ||
119 | + * @return string | ||
120 | + */ | ||
121 | + protected function get_class_from_file($path_to_file) | ||
122 | + { | ||
123 | + //Grab the contents of the file | ||
124 | + $contents = file_get_contents($path_to_file); | ||
125 | + | ||
126 | + //Start with a blank namespace and class | ||
127 | + $namespace = $class = ""; | ||
128 | + | ||
129 | + //Set helper values to know that we have found the namespace/class token and need to collect the string values after them | ||
130 | + $getting_namespace = $getting_class = false; | ||
131 | + | ||
132 | + //Go through each token and evaluate it as necessary | ||
133 | + foreach (token_get_all($contents) as $token) { | ||
134 | + | ||
135 | + //If this token is the namespace declaring, then flag that the next tokens will be the namespace name | ||
136 | + if (is_array($token) && $token[0] == T_NAMESPACE) { | ||
137 | + $getting_namespace = true; | ||
138 | + } | ||
139 | + | ||
140 | + //If this token is the class declaring, then flag that the next tokens will be the class name | ||
141 | + if (is_array($token) && $token[0] == T_CLASS) { | ||
142 | + $getting_class = true; | ||
143 | + } | ||
144 | + | ||
145 | + //While we're grabbing the namespace name... | ||
146 | + if ($getting_namespace === true) { | ||
147 | + | ||
148 | + //If the token is a string or the namespace separator... | ||
149 | + if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) { | ||
150 | + | ||
151 | + //Append the token's value to the name of the namespace | ||
152 | + $namespace .= $token[1]; | ||
153 | + } elseif ($token === ';') { | ||
154 | + | ||
155 | + //If the token is the semicolon, then we're done with the namespace declaration | ||
156 | + $getting_namespace = false; | ||
157 | + } | ||
158 | + } | ||
159 | + | ||
160 | + //While we're grabbing the class name... | ||
161 | + if ($getting_class === true) { | ||
162 | + | ||
163 | + //If the token is a string, it's the name of the class | ||
164 | + if (is_array($token) && $token[0] == T_STRING) { | ||
165 | + | ||
166 | + //Store the token's value as the class name | ||
167 | + $class = $token[1]; | ||
168 | + | ||
169 | + //Got what we need, stope here | ||
170 | + break; | ||
171 | + } | ||
172 | + } | ||
173 | + } | ||
174 | + | ||
175 | + //Build the fully-qualified class name and return it | ||
176 | + return $namespace ? $namespace . '\\' . $class : $class; | ||
177 | + } | ||
178 | +} |
application/admin/command/Api/lang/zh-cn.php
0 → 100644
1 | +<?php | ||
2 | + | ||
3 | +return [ | ||
4 | + 'Info' => '基础信息', | ||
5 | + 'Sandbox' => '在线测试', | ||
6 | + 'Sampleoutput' => '返回示例', | ||
7 | + 'Headers' => 'Headers', | ||
8 | + 'Parameters' => '参数', | ||
9 | + 'Body' => '正文', | ||
10 | + 'Name' => '名称', | ||
11 | + 'Type' => '类型', | ||
12 | + 'Required' => '必选', | ||
13 | + 'Description' => '描述', | ||
14 | + 'Send' => '提交', | ||
15 | + 'Reset' => '重置', | ||
16 | + 'Tokentips' => 'Token在会员注册或登录后都会返回,WEB端同时存在于Cookie中', | ||
17 | + 'Apiurltips' => 'API接口URL', | ||
18 | + 'Savetips' => '点击保存后Token和Api url都将保存在本地Localstorage中', | ||
19 | + 'ReturnHeaders' => '响应头', | ||
20 | + 'ReturnParameters' => '返回参数', | ||
21 | + 'Response' => '响应输出', | ||
22 | +]; |
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command\Api\library; | ||
4 | + | ||
5 | +use think\Config; | ||
6 | + | ||
7 | +/** | ||
8 | + * @website https://github.com/calinrada/php-apidoc | ||
9 | + * @author Calin Rada <rada.calin@gmail.com> | ||
10 | + * @author Karson <karsonzhang@163.com> | ||
11 | + */ | ||
12 | +class Builder | ||
13 | +{ | ||
14 | + | ||
15 | + /** | ||
16 | + * | ||
17 | + * @var \think\View | ||
18 | + */ | ||
19 | + public $view = null; | ||
20 | + | ||
21 | + /** | ||
22 | + * parse classes | ||
23 | + * @var array | ||
24 | + */ | ||
25 | + protected $classes = []; | ||
26 | + | ||
27 | + /** | ||
28 | + * | ||
29 | + * @param array $classes | ||
30 | + */ | ||
31 | + public function __construct($classes = []) | ||
32 | + { | ||
33 | + $this->classes = array_merge($this->classes, $classes); | ||
34 | + $this->view = new \think\View(Config::get('template'), Config::get('view_replace_str')); | ||
35 | + } | ||
36 | + | ||
37 | + protected function extractAnnotations() | ||
38 | + { | ||
39 | + foreach ($this->classes as $class) { | ||
40 | + $classAnnotation = Extractor::getClassAnnotations($class); | ||
41 | + // 如果忽略 | ||
42 | + if (isset($classAnnotation['ApiInternal'])) { | ||
43 | + continue; | ||
44 | + } | ||
45 | + Extractor::getClassMethodAnnotations($class); | ||
46 | + } | ||
47 | + $allClassAnnotation = Extractor::getAllClassAnnotations(); | ||
48 | + $allClassMethodAnnotation = Extractor::getAllClassMethodAnnotations(); | ||
49 | + | ||
50 | +// foreach ($allClassMethodAnnotation as $className => &$methods) { | ||
51 | +// foreach ($methods as &$method) { | ||
52 | +// //权重判断 | ||
53 | +// if ($method && !isset($method['ApiWeigh']) && isset($allClassAnnotation[$className]['ApiWeigh'])) { | ||
54 | +// $method['ApiWeigh'] = $allClassAnnotation[$className]['ApiWeigh']; | ||
55 | +// } | ||
56 | +// } | ||
57 | +// } | ||
58 | +// unset($methods); | ||
59 | + return [$allClassAnnotation, $allClassMethodAnnotation]; | ||
60 | + } | ||
61 | + | ||
62 | + protected function generateHeadersTemplate($docs) | ||
63 | + { | ||
64 | + if (!isset($docs['ApiHeaders'])) { | ||
65 | + return []; | ||
66 | + } | ||
67 | + | ||
68 | + $headerslist = array(); | ||
69 | + foreach ($docs['ApiHeaders'] as $params) { | ||
70 | + $tr = array( | ||
71 | + 'name' => $params['name'], | ||
72 | + 'type' => $params['type'], | ||
73 | + 'sample' => isset($params['sample']) ? $params['sample'] : '', | ||
74 | + 'required' => isset($params['required']) ? $params['required'] : false, | ||
75 | + 'description' => isset($params['description']) ? $params['description'] : '', | ||
76 | + ); | ||
77 | + $headerslist[] = $tr; | ||
78 | + } | ||
79 | + | ||
80 | + return $headerslist; | ||
81 | + } | ||
82 | + | ||
83 | + protected function generateParamsTemplate($docs) | ||
84 | + { | ||
85 | + if (!isset($docs['ApiParams'])) { | ||
86 | + return []; | ||
87 | + } | ||
88 | + | ||
89 | + $paramslist = array(); | ||
90 | + foreach ($docs['ApiParams'] as $params) { | ||
91 | + $tr = array( | ||
92 | + 'name' => $params['name'], | ||
93 | + 'type' => isset($params['type']) ? $params['type'] : 'string', | ||
94 | + 'sample' => isset($params['sample']) ? $params['sample'] : '', | ||
95 | + 'required' => isset($params['required']) ? $params['required'] : true, | ||
96 | + 'description' => isset($params['description']) ? $params['description'] : '', | ||
97 | + ); | ||
98 | + $paramslist[] = $tr; | ||
99 | + } | ||
100 | + | ||
101 | + return $paramslist; | ||
102 | + } | ||
103 | + | ||
104 | + protected function generateReturnHeadersTemplate($docs) | ||
105 | + { | ||
106 | + if (!isset($docs['ApiReturnHeaders'])) { | ||
107 | + return []; | ||
108 | + } | ||
109 | + | ||
110 | + $headerslist = array(); | ||
111 | + foreach ($docs['ApiReturnHeaders'] as $params) { | ||
112 | + $tr = array( | ||
113 | + 'name' => $params['name'], | ||
114 | + 'type' => 'string', | ||
115 | + 'sample' => isset($params['sample']) ? $params['sample'] : '', | ||
116 | + 'required' => isset($params['required']) && $params['required'] ? 'Yes' : 'No', | ||
117 | + 'description' => isset($params['description']) ? $params['description'] : '', | ||
118 | + ); | ||
119 | + $headerslist[] = $tr; | ||
120 | + } | ||
121 | + | ||
122 | + return $headerslist; | ||
123 | + } | ||
124 | + | ||
125 | + protected function generateReturnParamsTemplate($st_params) | ||
126 | + { | ||
127 | + if (!isset($st_params['ApiReturnParams'])) { | ||
128 | + return []; | ||
129 | + } | ||
130 | + | ||
131 | + $paramslist = array(); | ||
132 | + foreach ($st_params['ApiReturnParams'] as $params) { | ||
133 | + $tr = array( | ||
134 | + 'name' => $params['name'], | ||
135 | + 'type' => isset($params['type']) ? $params['type'] : 'string', | ||
136 | + 'sample' => isset($params['sample']) ? $params['sample'] : '', | ||
137 | + 'description' => isset($params['description']) ? $params['description'] : '', | ||
138 | + ); | ||
139 | + $paramslist[] = $tr; | ||
140 | + } | ||
141 | + | ||
142 | + return $paramslist; | ||
143 | + } | ||
144 | + | ||
145 | + protected function generateBadgeForMethod($data) | ||
146 | + { | ||
147 | + $method = strtoupper(is_array($data['ApiMethod'][0]) ? $data['ApiMethod'][0]['data'] : $data['ApiMethod'][0]); | ||
148 | + $labes = array( | ||
149 | + 'POST' => 'label-primary', | ||
150 | + 'GET' => 'label-success', | ||
151 | + 'PUT' => 'label-warning', | ||
152 | + 'DELETE' => 'label-danger', | ||
153 | + 'PATCH' => 'label-default', | ||
154 | + 'OPTIONS' => 'label-info' | ||
155 | + ); | ||
156 | + | ||
157 | + return isset($labes[$method]) ? $labes[$method] : $labes['GET']; | ||
158 | + } | ||
159 | + | ||
160 | + public function parse() | ||
161 | + { | ||
162 | + list($allClassAnnotations, $allClassMethodAnnotations) = $this->extractAnnotations(); | ||
163 | + | ||
164 | + $sectorArr = []; | ||
165 | + foreach ($allClassAnnotations as $index => $allClassAnnotation) { | ||
166 | + $sector = isset($allClassAnnotation['ApiSector']) ? $allClassAnnotation['ApiSector'][0] : $allClassAnnotation['ApiTitle'][0]; | ||
167 | + $sectorArr[$sector] = isset($allClassAnnotation['ApiWeigh']) ? $allClassAnnotation['ApiWeigh'][0] : 0; | ||
168 | + } | ||
169 | + arsort($sectorArr); | ||
170 | + $routes = include_once CONF_PATH . 'route.php'; | ||
171 | + $subdomain = false; | ||
172 | + if (config('url_domain_deploy') && isset($routes['__domain__']) && isset($routes['__domain__']['api']) && $routes['__domain__']['api']) { | ||
173 | + $subdomain = true; | ||
174 | + } | ||
175 | + $counter = 0; | ||
176 | + $section = null; | ||
177 | + $weigh = 0; | ||
178 | + $docslist = []; | ||
179 | + foreach ($allClassMethodAnnotations as $class => $methods) { | ||
180 | + foreach ($methods as $name => $docs) { | ||
181 | + if (isset($docs['ApiSector'][0])) { | ||
182 | + $section = is_array($docs['ApiSector'][0]) ? $docs['ApiSector'][0]['data'] : $docs['ApiSector'][0]; | ||
183 | + } else { | ||
184 | + $section = $class; | ||
185 | + } | ||
186 | + if (0 === count($docs)) { | ||
187 | + continue; | ||
188 | + } | ||
189 | + $route = is_array($docs['ApiRoute'][0]) ? $docs['ApiRoute'][0]['data'] : $docs['ApiRoute'][0]; | ||
190 | + if ($subdomain) { | ||
191 | + $route = substr($route, 4); | ||
192 | + } | ||
193 | + $docslist[$section][$name] = [ | ||
194 | + 'id' => $counter, | ||
195 | + 'method' => is_array($docs['ApiMethod'][0]) ? $docs['ApiMethod'][0]['data'] : $docs['ApiMethod'][0], | ||
196 | + 'method_label' => $this->generateBadgeForMethod($docs), | ||
197 | + 'section' => $section, | ||
198 | + 'route' => $route, | ||
199 | + 'title' => is_array($docs['ApiTitle'][0]) ? $docs['ApiTitle'][0]['data'] : $docs['ApiTitle'][0], | ||
200 | + 'summary' => is_array($docs['ApiSummary'][0]) ? $docs['ApiSummary'][0]['data'] : $docs['ApiSummary'][0], | ||
201 | + 'body' => isset($docs['ApiBody'][0]) ? is_array($docs['ApiBody'][0]) ? $docs['ApiBody'][0]['data'] : $docs['ApiBody'][0] : '', | ||
202 | + 'headerslist' => $this->generateHeadersTemplate($docs), | ||
203 | + 'paramslist' => $this->generateParamsTemplate($docs), | ||
204 | + 'returnheaderslist' => $this->generateReturnHeadersTemplate($docs), | ||
205 | + 'returnparamslist' => $this->generateReturnParamsTemplate($docs), | ||
206 | + 'weigh' => is_array($docs['ApiWeigh'][0]) ? $docs['ApiWeigh'][0]['data'] : $docs['ApiWeigh'][0], | ||
207 | + 'return' => isset($docs['ApiReturn']) ? is_array($docs['ApiReturn'][0]) ? $docs['ApiReturn'][0]['data'] : $docs['ApiReturn'][0] : '', | ||
208 | + ]; | ||
209 | + $counter++; | ||
210 | + } | ||
211 | + } | ||
212 | + | ||
213 | + //重建排序 | ||
214 | + foreach ($docslist as $index => &$methods) { | ||
215 | + $methodSectorArr = []; | ||
216 | + foreach ($methods as $name => $method) { | ||
217 | + $methodSectorArr[$name] = isset($method['weigh']) ? $method['weigh'] : 0; | ||
218 | + } | ||
219 | + arsort($methodSectorArr); | ||
220 | + $methods = array_merge(array_flip(array_keys($methodSectorArr)), $methods); | ||
221 | + } | ||
222 | + $docslist = array_merge(array_flip(array_keys($sectorArr)), $docslist); | ||
223 | + | ||
224 | + return $docslist; | ||
225 | + } | ||
226 | + | ||
227 | + public function getView() | ||
228 | + { | ||
229 | + return $this->view; | ||
230 | + } | ||
231 | + | ||
232 | + /** | ||
233 | + * 渲染 | ||
234 | + * @param string $template | ||
235 | + * @param array $vars | ||
236 | + * @return string | ||
237 | + */ | ||
238 | + public function render($template, $vars = []) | ||
239 | + { | ||
240 | + $docslist = $this->parse(); | ||
241 | + | ||
242 | + return $this->view->display(file_get_contents($template), array_merge($vars, ['docslist' => $docslist])); | ||
243 | + } | ||
244 | +} |
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command\Api\library; | ||
4 | + | ||
5 | +use Exception; | ||
6 | + | ||
7 | +/** | ||
8 | + * Class imported from https://github.com/eriknyk/Annotations | ||
9 | + * @author Erik Amaru Ortiz https://github.com/eriknyk | ||
10 | + * | ||
11 | + * @license http://opensource.org/licenses/bsd-license.php The BSD License | ||
12 | + * @author Calin Rada <rada.calin@gmail.com> | ||
13 | + */ | ||
14 | +class Extractor | ||
15 | +{ | ||
16 | + | ||
17 | + /** | ||
18 | + * Static array to store already parsed annotations | ||
19 | + * @var array | ||
20 | + */ | ||
21 | + private static $annotationCache; | ||
22 | + | ||
23 | + private static $classAnnotationCache; | ||
24 | + | ||
25 | + private static $classMethodAnnotationCache; | ||
26 | + | ||
27 | + /** | ||
28 | + * Indicates that annotations should has strict behavior, 'false' by default | ||
29 | + * @var boolean | ||
30 | + */ | ||
31 | + private $strict = false; | ||
32 | + | ||
33 | + /** | ||
34 | + * Stores the default namespace for Objects instance, usually used on methods like getMethodAnnotationsObjects() | ||
35 | + * @var string | ||
36 | + */ | ||
37 | + public $defaultNamespace = ''; | ||
38 | + | ||
39 | + /** | ||
40 | + * Sets strict variable to true/false | ||
41 | + * @param bool $value boolean value to indicate that annotations to has strict behavior | ||
42 | + */ | ||
43 | + public function setStrict($value) | ||
44 | + { | ||
45 | + $this->strict = (bool)$value; | ||
46 | + } | ||
47 | + | ||
48 | + /** | ||
49 | + * Sets default namespace to use in object instantiation | ||
50 | + * @param string $namespace default namespace | ||
51 | + */ | ||
52 | + public function setDefaultNamespace($namespace) | ||
53 | + { | ||
54 | + $this->defaultNamespace = $namespace; | ||
55 | + } | ||
56 | + | ||
57 | + /** | ||
58 | + * Gets default namespace used in object instantiation | ||
59 | + * @return string $namespace default namespace | ||
60 | + */ | ||
61 | + public function getDefaultAnnotationNamespace() | ||
62 | + { | ||
63 | + return $this->defaultNamespace; | ||
64 | + } | ||
65 | + | ||
66 | + /** | ||
67 | + * Gets all anotations with pattern @SomeAnnotation() from a given class | ||
68 | + * | ||
69 | + * @param string $className class name to get annotations | ||
70 | + * @return array self::$classAnnotationCache all annotated elements | ||
71 | + */ | ||
72 | + public static function getClassAnnotations($className) | ||
73 | + { | ||
74 | + if (!isset(self::$classAnnotationCache[$className])) { | ||
75 | + $class = new \ReflectionClass($className); | ||
76 | + self::$classAnnotationCache[$className] = self::parseAnnotations($class->getDocComment()); | ||
77 | + } | ||
78 | + | ||
79 | + return self::$classAnnotationCache[$className]; | ||
80 | + } | ||
81 | + | ||
82 | + /** | ||
83 | + * 获取类所有方法的属性配置 | ||
84 | + * @param $className | ||
85 | + * @return mixed | ||
86 | + * @throws \ReflectionException | ||
87 | + */ | ||
88 | + public static function getClassMethodAnnotations($className) | ||
89 | + { | ||
90 | + $class = new \ReflectionClass($className); | ||
91 | + | ||
92 | + foreach ($class->getMethods() as $object) { | ||
93 | + self::$classMethodAnnotationCache[$className][$object->name] = self::getMethodAnnotations($className, $object->name); | ||
94 | + } | ||
95 | + | ||
96 | + return self::$classMethodAnnotationCache[$className]; | ||
97 | + } | ||
98 | + | ||
99 | + public static function getAllClassAnnotations() | ||
100 | + { | ||
101 | + return self::$classAnnotationCache; | ||
102 | + } | ||
103 | + | ||
104 | + public static function getAllClassMethodAnnotations() | ||
105 | + { | ||
106 | + return self::$classMethodAnnotationCache; | ||
107 | + } | ||
108 | + | ||
109 | + /** | ||
110 | + * Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class | ||
111 | + * | ||
112 | + * @param string $className class name | ||
113 | + * @param string $methodName method name to get annotations | ||
114 | + * @return array self::$annotationCache all annotated elements of a method given | ||
115 | + */ | ||
116 | + public static function getMethodAnnotations($className, $methodName) | ||
117 | + { | ||
118 | + if (!isset(self::$annotationCache[$className . '::' . $methodName])) { | ||
119 | + try { | ||
120 | + $method = new \ReflectionMethod($className, $methodName); | ||
121 | + $class = new \ReflectionClass($className); | ||
122 | + if (!$method->isPublic() || $method->isConstructor()) { | ||
123 | + $annotations = array(); | ||
124 | + } else { | ||
125 | + $annotations = self::consolidateAnnotations($method, $class); | ||
126 | + } | ||
127 | + } catch (\ReflectionException $e) { | ||
128 | + $annotations = array(); | ||
129 | + } | ||
130 | + | ||
131 | + self::$annotationCache[$className . '::' . $methodName] = $annotations; | ||
132 | + } | ||
133 | + | ||
134 | + return self::$annotationCache[$className . '::' . $methodName]; | ||
135 | + } | ||
136 | + | ||
137 | + /** | ||
138 | + * Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class | ||
139 | + * and instance its abcAnnotation class | ||
140 | + * | ||
141 | + * @param string $className class name | ||
142 | + * @param string $methodName method name to get annotations | ||
143 | + * @return array self::$annotationCache all annotated objects of a method given | ||
144 | + */ | ||
145 | + public function getMethodAnnotationsObjects($className, $methodName) | ||
146 | + { | ||
147 | + $annotations = $this->getMethodAnnotations($className, $methodName); | ||
148 | + $objects = array(); | ||
149 | + | ||
150 | + $i = 0; | ||
151 | + | ||
152 | + foreach ($annotations as $annotationClass => $listParams) { | ||
153 | + $annotationClass = ucfirst($annotationClass); | ||
154 | + $class = $this->defaultNamespace . $annotationClass . 'Annotation'; | ||
155 | + | ||
156 | + // verify is the annotation class exists, depending if Annotations::strict is true | ||
157 | + // if not, just skip the annotation instance creation. | ||
158 | + if (!class_exists($class)) { | ||
159 | + if ($this->strict) { | ||
160 | + throw new Exception(sprintf('Runtime Error: Annotation Class Not Found: %s', $class)); | ||
161 | + } else { | ||
162 | + // silent skip & continue | ||
163 | + continue; | ||
164 | + } | ||
165 | + } | ||
166 | + | ||
167 | + if (empty($objects[$annotationClass])) { | ||
168 | + $objects[$annotationClass] = new $class(); | ||
169 | + } | ||
170 | + | ||
171 | + foreach ($listParams as $params) { | ||
172 | + if (is_array($params)) { | ||
173 | + foreach ($params as $key => $value) { | ||
174 | + $objects[$annotationClass]->set($key, $value); | ||
175 | + } | ||
176 | + } else { | ||
177 | + $objects[$annotationClass]->set($i++, $params); | ||
178 | + } | ||
179 | + } | ||
180 | + } | ||
181 | + | ||
182 | + return $objects; | ||
183 | + } | ||
184 | + | ||
185 | + private static function consolidateAnnotations($method, $class) | ||
186 | + { | ||
187 | + $dockblockClass = $class->getDocComment(); | ||
188 | + $docblockMethod = $method->getDocComment(); | ||
189 | + $methodName = $method->getName(); | ||
190 | + | ||
191 | + $methodAnnotations = self::parseAnnotations($docblockMethod); | ||
192 | + $classAnnotations = self::parseAnnotations($dockblockClass); | ||
193 | + if (isset($methodAnnotations['ApiInternal']) || $methodName == '_initialize' || $methodName == '_empty') { | ||
194 | + return []; | ||
195 | + } | ||
196 | + | ||
197 | + $properties = $class->getDefaultProperties(); | ||
198 | + $noNeedLogin = isset($properties['noNeedLogin']) ? is_array($properties['noNeedLogin']) ? $properties['noNeedLogin'] : [$properties['noNeedLogin']] : []; | ||
199 | + $noNeedRight = isset($properties['noNeedRight']) ? is_array($properties['noNeedRight']) ? $properties['noNeedRight'] : [$properties['noNeedRight']] : []; | ||
200 | + | ||
201 | + preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $docblockMethod), $methodArr); | ||
202 | + preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $dockblockClass), $classArr); | ||
203 | + | ||
204 | + if (!isset($methodAnnotations['ApiMethod'])) { | ||
205 | + $methodAnnotations['ApiMethod'] = ['get']; | ||
206 | + } | ||
207 | + if (!isset($methodAnnotations['ApiWeigh'])) { | ||
208 | + $methodAnnotations['ApiWeigh'] = [0]; | ||
209 | + } | ||
210 | + if (!isset($methodAnnotations['ApiSummary'])) { | ||
211 | + $methodAnnotations['ApiSummary'] = $methodAnnotations['ApiTitle']; | ||
212 | + } | ||
213 | + | ||
214 | + if ($methodAnnotations) { | ||
215 | + foreach ($classAnnotations as $name => $valueClass) { | ||
216 | + if (count($valueClass) !== 1) { | ||
217 | + continue; | ||
218 | + } | ||
219 | + | ||
220 | + if ($name === 'ApiRoute') { | ||
221 | + if (isset($methodAnnotations[$name])) { | ||
222 | + $methodAnnotations[$name] = [rtrim($valueClass[0], '/') . $methodAnnotations[$name][0]]; | ||
223 | + } else { | ||
224 | + $methodAnnotations[$name] = [rtrim($valueClass[0], '/') . '/' . $method->getName()]; | ||
225 | + } | ||
226 | + } | ||
227 | + | ||
228 | + if ($name === 'ApiSector') { | ||
229 | + $methodAnnotations[$name] = $valueClass; | ||
230 | + } | ||
231 | + } | ||
232 | + } | ||
233 | + if (!isset($methodAnnotations['ApiRoute'])) { | ||
234 | + $urlArr = []; | ||
235 | + $className = $class->getName(); | ||
236 | + | ||
237 | + list($prefix, $suffix) = explode('\\' . \think\Config::get('url_controller_layer') . '\\', $className); | ||
238 | + $prefixArr = explode('\\', $prefix); | ||
239 | + $suffixArr = explode('\\', $suffix); | ||
240 | + if ($prefixArr[0] == \think\Config::get('app_namespace')) { | ||
241 | + $prefixArr[0] = ''; | ||
242 | + } | ||
243 | + $urlArr = array_merge($urlArr, $prefixArr); | ||
244 | + $urlArr[] = implode('.', array_map(function ($item) { | ||
245 | + return \think\Loader::parseName($item); | ||
246 | + }, $suffixArr)); | ||
247 | + $urlArr[] = $method->getName(); | ||
248 | + | ||
249 | + $methodAnnotations['ApiRoute'] = [implode('/', $urlArr)]; | ||
250 | + } | ||
251 | + if (!isset($methodAnnotations['ApiSector'])) { | ||
252 | + $methodAnnotations['ApiSector'] = isset($classAnnotations['ApiSector']) ? $classAnnotations['ApiSector'] : $classAnnotations['ApiTitle']; | ||
253 | + } | ||
254 | + if (!isset($methodAnnotations['ApiParams'])) { | ||
255 | + $params = self::parseCustomAnnotations($docblockMethod, 'param'); | ||
256 | + foreach ($params as $k => $v) { | ||
257 | + $arr = explode(' ', preg_replace("/[\s]+/", " ", $v)); | ||
258 | + $methodAnnotations['ApiParams'][] = [ | ||
259 | + 'name' => isset($arr[1]) ? str_replace('$', '', $arr[1]) : '', | ||
260 | + 'nullable' => false, | ||
261 | + 'type' => isset($arr[0]) ? $arr[0] : 'string', | ||
262 | + 'description' => isset($arr[2]) ? $arr[2] : '' | ||
263 | + ]; | ||
264 | + } | ||
265 | + } | ||
266 | + $methodAnnotations['ApiPermissionLogin'] = [!in_array('*', $noNeedLogin) && !in_array($methodName, $noNeedLogin)]; | ||
267 | + $methodAnnotations['ApiPermissionRight'] = [!in_array('*', $noNeedRight) && !in_array($methodName, $noNeedRight)]; | ||
268 | + return $methodAnnotations; | ||
269 | + } | ||
270 | + | ||
271 | + /** | ||
272 | + * Parse annotations | ||
273 | + * | ||
274 | + * @param string $docblock | ||
275 | + * @param string $name | ||
276 | + * @return array parsed annotations params | ||
277 | + */ | ||
278 | + private static function parseCustomAnnotations($docblock, $name = 'param') | ||
279 | + { | ||
280 | + $annotations = array(); | ||
281 | + | ||
282 | + $docblock = substr($docblock, 3, -2); | ||
283 | + if (preg_match_all('/@' . $name . '(?:\s*(?:\(\s*)?(.*?)(?:\s*\))?)??\s*(?:\n|\*\/)/', $docblock, $matches)) { | ||
284 | + foreach ($matches[1] as $k => $v) { | ||
285 | + $annotations[] = $v; | ||
286 | + } | ||
287 | + } | ||
288 | + return $annotations; | ||
289 | + } | ||
290 | + | ||
291 | + /** | ||
292 | + * Parse annotations | ||
293 | + * | ||
294 | + * @param string $docblock | ||
295 | + * @return array parsed annotations params | ||
296 | + */ | ||
297 | + private static function parseAnnotations($docblock) | ||
298 | + { | ||
299 | + $annotations = array(); | ||
300 | + | ||
301 | + // Strip away the docblock header and footer to ease parsing of one line annotations | ||
302 | + $docblock = substr($docblock, 3, -2); | ||
303 | + if (preg_match_all('/@(?<name>[A-Za-z_-]+)[\s\t]*\((?<args>(?:(?!\)).)*)\)\r?/s', $docblock, $matches)) { | ||
304 | + $numMatches = count($matches[0]); | ||
305 | + for ($i = 0; $i < $numMatches; ++$i) { | ||
306 | + $name = $matches['name'][$i]; | ||
307 | + $value = ''; | ||
308 | + // annotations has arguments | ||
309 | + if (isset($matches['args'][$i])) { | ||
310 | + $argsParts = trim($matches['args'][$i]); | ||
311 | + if ($name == 'ApiReturn') { | ||
312 | + $value = $argsParts; | ||
313 | + } elseif ($matches['args'][$i] != '') { | ||
314 | + $argsParts = preg_replace("/\{(\w+)\}/", '#$1#', $argsParts); | ||
315 | + $value = self::parseArgs($argsParts); | ||
316 | + if (is_string($value)) { | ||
317 | + $value = preg_replace("/\#(\w+)\#/", '{$1}', $argsParts); | ||
318 | + } | ||
319 | + } | ||
320 | + } | ||
321 | + | ||
322 | + $annotations[$name][] = $value; | ||
323 | + } | ||
324 | + } | ||
325 | + if (stripos($docblock, '@ApiInternal') !== false) { | ||
326 | + $annotations['ApiInternal'] = [true]; | ||
327 | + } | ||
328 | + if (!isset($annotations['ApiTitle'])) { | ||
329 | + preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $docblock), $matchArr); | ||
330 | + $title = isset($matchArr[1]) && isset($matchArr[1][0]) ? $matchArr[1][0] : ''; | ||
331 | + $annotations['ApiTitle'] = [$title]; | ||
332 | + } | ||
333 | + | ||
334 | + return $annotations; | ||
335 | + } | ||
336 | + | ||
337 | + /** | ||
338 | + * Parse individual annotation arguments | ||
339 | + * | ||
340 | + * @param string $content arguments string | ||
341 | + * @return array annotated arguments | ||
342 | + */ | ||
343 | + private static function parseArgs($content) | ||
344 | + { | ||
345 | + // Replace initial stars | ||
346 | + $content = preg_replace('/^\s*\*/m', '', $content); | ||
347 | + | ||
348 | + $data = array(); | ||
349 | + $len = strlen($content); | ||
350 | + $i = 0; | ||
351 | + $var = ''; | ||
352 | + $val = ''; | ||
353 | + $level = 1; | ||
354 | + | ||
355 | + $prevDelimiter = ''; | ||
356 | + $nextDelimiter = ''; | ||
357 | + $nextToken = ''; | ||
358 | + $composing = false; | ||
359 | + $type = 'plain'; | ||
360 | + $delimiter = null; | ||
361 | + $quoted = false; | ||
362 | + $tokens = array('"', '"', '{', '}', ',', '='); | ||
363 | + | ||
364 | + while ($i <= $len) { | ||
365 | + $prev_c = substr($content, $i - 1, 1); | ||
366 | + $c = substr($content, $i++, 1); | ||
367 | + | ||
368 | + if ($c === '"' && $prev_c !== "\\") { | ||
369 | + $delimiter = $c; | ||
370 | + //open delimiter | ||
371 | + if (!$composing && empty($prevDelimiter) && empty($nextDelimiter)) { | ||
372 | + $prevDelimiter = $nextDelimiter = $delimiter; | ||
373 | + $val = ''; | ||
374 | + $composing = true; | ||
375 | + $quoted = true; | ||
376 | + } else { | ||
377 | + // close delimiter | ||
378 | + if ($c !== $nextDelimiter) { | ||
379 | + throw new Exception(sprintf( | ||
380 | + "Parse Error: enclosing error -> expected: [%s], given: [%s]", | ||
381 | + $nextDelimiter, | ||
382 | + $c | ||
383 | + )); | ||
384 | + } | ||
385 | + | ||
386 | + // validating syntax | ||
387 | + if ($i < $len) { | ||
388 | + if (',' !== substr($content, $i, 1) && '\\' !== $prev_c) { | ||
389 | + throw new Exception(sprintf( | ||
390 | + "Parse Error: missing comma separator near: ...%s<--", | ||
391 | + substr($content, ($i - 10), $i) | ||
392 | + )); | ||
393 | + } | ||
394 | + } | ||
395 | + | ||
396 | + $prevDelimiter = $nextDelimiter = ''; | ||
397 | + $composing = false; | ||
398 | + $delimiter = null; | ||
399 | + } | ||
400 | + } elseif (!$composing && in_array($c, $tokens)) { | ||
401 | + switch ($c) { | ||
402 | + case '=': | ||
403 | + $prevDelimiter = $nextDelimiter = ''; | ||
404 | + $level = 2; | ||
405 | + $composing = false; | ||
406 | + $type = 'assoc'; | ||
407 | + $quoted = false; | ||
408 | + break; | ||
409 | + case ',': | ||
410 | + $level = 3; | ||
411 | + | ||
412 | + // If composing flag is true yet, | ||
413 | + // it means that the string was not enclosed, so it is parsing error. | ||
414 | + if ($composing === true && !empty($prevDelimiter) && !empty($nextDelimiter)) { | ||
415 | + throw new Exception(sprintf( | ||
416 | + "Parse Error: enclosing error -> expected: [%s], given: [%s]", | ||
417 | + $nextDelimiter, | ||
418 | + $c | ||
419 | + )); | ||
420 | + } | ||
421 | + | ||
422 | + $prevDelimiter = $nextDelimiter = ''; | ||
423 | + break; | ||
424 | + case '{': | ||
425 | + $subc = ''; | ||
426 | + $subComposing = true; | ||
427 | + | ||
428 | + while ($i <= $len) { | ||
429 | + $c = substr($content, $i++, 1); | ||
430 | + | ||
431 | + if (isset($delimiter) && $c === $delimiter) { | ||
432 | + throw new Exception(sprintf( | ||
433 | + "Parse Error: Composite variable is not enclosed correctly." | ||
434 | + )); | ||
435 | + } | ||
436 | + | ||
437 | + if ($c === '}') { | ||
438 | + $subComposing = false; | ||
439 | + break; | ||
440 | + } | ||
441 | + $subc .= $c; | ||
442 | + } | ||
443 | + | ||
444 | + // if the string is composing yet means that the structure of var. never was enclosed with '}' | ||
445 | + if ($subComposing) { | ||
446 | + throw new Exception(sprintf( | ||
447 | + "Parse Error: Composite variable is not enclosed correctly. near: ...%s'", | ||
448 | + $subc | ||
449 | + )); | ||
450 | + } | ||
451 | + | ||
452 | + $val = self::parseArgs($subc); | ||
453 | + break; | ||
454 | + } | ||
455 | + } else { | ||
456 | + if ($level == 1) { | ||
457 | + $var .= $c; | ||
458 | + } elseif ($level == 2) { | ||
459 | + $val .= $c; | ||
460 | + } | ||
461 | + } | ||
462 | + | ||
463 | + if ($level === 3 || $i === $len) { | ||
464 | + if ($type == 'plain' && $i === $len) { | ||
465 | + $data = self::castValue($var); | ||
466 | + } else { | ||
467 | + $data[trim($var)] = self::castValue($val, !$quoted); | ||
468 | + } | ||
469 | + | ||
470 | + $level = 1; | ||
471 | + $var = $val = ''; | ||
472 | + $composing = false; | ||
473 | + $quoted = false; | ||
474 | + } | ||
475 | + } | ||
476 | + | ||
477 | + return $data; | ||
478 | + } | ||
479 | + | ||
480 | + /** | ||
481 | + * Try determinate the original type variable of a string | ||
482 | + * | ||
483 | + * @param string $val string containing possibles variables that can be cast to bool or int | ||
484 | + * @param boolean $trim indicate if the value passed should be trimmed after to try cast | ||
485 | + * @return mixed returns the value converted to original type if was possible | ||
486 | + */ | ||
487 | + private static function castValue($val, $trim = false) | ||
488 | + { | ||
489 | + if (is_array($val)) { | ||
490 | + foreach ($val as $key => $value) { | ||
491 | + $val[$key] = self::castValue($value); | ||
492 | + } | ||
493 | + } elseif (is_string($val)) { | ||
494 | + if ($trim) { | ||
495 | + $val = trim($val); | ||
496 | + } | ||
497 | + $val = stripslashes($val); | ||
498 | + $tmp = strtolower($val); | ||
499 | + | ||
500 | + if ($tmp === 'false' || $tmp === 'true') { | ||
501 | + $val = $tmp === 'true'; | ||
502 | + } elseif (is_numeric($val)) { | ||
503 | + return $val + 0; | ||
504 | + } | ||
505 | + | ||
506 | + unset($tmp); | ||
507 | + } | ||
508 | + | ||
509 | + return $val; | ||
510 | + } | ||
511 | +} |
1 | +<!DOCTYPE html> | ||
2 | +<html lang="{$config.language}"> | ||
3 | + <head> | ||
4 | + <meta charset="utf-8"> | ||
5 | + <meta http-equiv="X-UA-Compatible" content="IE=edge"> | ||
6 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
7 | + <meta name="description" content=""> | ||
8 | + <meta name="author" content="{$config.author}"> | ||
9 | + <title>{$config.title}</title> | ||
10 | + | ||
11 | + <!-- Bootstrap Core CSS --> | ||
12 | + <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> | ||
13 | + | ||
14 | + <!-- Plugin CSS --> | ||
15 | + <link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> | ||
16 | + | ||
17 | + <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> | ||
18 | + <!--[if lt IE 9]> | ||
19 | + <script src="https://cdn.staticfile.org/html5shiv/3.7.3/html5shiv.min.js"></script> | ||
20 | + <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script> | ||
21 | + <![endif]--> | ||
22 | + | ||
23 | + <style type="text/css"> | ||
24 | + body { | ||
25 | + padding-top: 70px; margin-bottom: 15px; | ||
26 | + -webkit-font-smoothing: antialiased; | ||
27 | + -moz-osx-font-smoothing: grayscale; | ||
28 | + font-family: "Roboto", "SF Pro SC", "SF Pro Display", "SF Pro Icons", "PingFang SC", BlinkMacSystemFont, -apple-system, "Segoe UI", "Microsoft Yahei", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif; | ||
29 | + font-weight: 400; | ||
30 | + } | ||
31 | + h2 { font-size: 1.6em; } | ||
32 | + hr { margin-top: 10px; } | ||
33 | + .tab-pane { padding-top: 10px; } | ||
34 | + .mt0 { margin-top: 0px; } | ||
35 | + .footer { font-size: 12px; color: #666; } | ||
36 | + .label { display: inline-block; min-width: 65px; padding: 0.3em 0.6em 0.3em; } | ||
37 | + .string { color: green; } | ||
38 | + .number { color: darkorange; } | ||
39 | + .boolean { color: blue; } | ||
40 | + .null { color: magenta; } | ||
41 | + .key { color: red; } | ||
42 | + .popover { max-width: 400px; max-height: 400px; overflow-y: auto;} | ||
43 | + .list-group.panel > .list-group-item { | ||
44 | + } | ||
45 | + .list-group-item:last-child { | ||
46 | + border-radius:0; | ||
47 | + } | ||
48 | + h4.panel-title a { | ||
49 | + font-weight:normal; | ||
50 | + font-size:14px; | ||
51 | + } | ||
52 | + h4.panel-title a .text-muted { | ||
53 | + font-size:12px; | ||
54 | + font-weight:normal; | ||
55 | + font-family: 'Verdana'; | ||
56 | + } | ||
57 | + #sidebar { | ||
58 | + width: 220px; | ||
59 | + position: fixed; | ||
60 | + margin-left: -240px; | ||
61 | + overflow-y:auto; | ||
62 | + } | ||
63 | + #sidebar > .list-group { | ||
64 | + margin-bottom:0; | ||
65 | + } | ||
66 | + #sidebar > .list-group > a{ | ||
67 | + text-indent:0; | ||
68 | + } | ||
69 | + #sidebar .child { | ||
70 | + border:1px solid #ddd; | ||
71 | + border-bottom:none; | ||
72 | + } | ||
73 | + #sidebar .child > a { | ||
74 | + border:0; | ||
75 | + } | ||
76 | + #sidebar .list-group a.current { | ||
77 | + background:#f5f5f5; | ||
78 | + } | ||
79 | + @media (max-width: 1620px){ | ||
80 | + #sidebar { | ||
81 | + margin:0; | ||
82 | + } | ||
83 | + #accordion { | ||
84 | + padding-left:235px; | ||
85 | + } | ||
86 | + } | ||
87 | + @media (max-width: 768px){ | ||
88 | + #sidebar { | ||
89 | + display: none; | ||
90 | + } | ||
91 | + #accordion { | ||
92 | + padding-left:0px; | ||
93 | + } | ||
94 | + } | ||
95 | + .label-primary { | ||
96 | + background-color: #248aff; | ||
97 | + } | ||
98 | + | ||
99 | + </style> | ||
100 | + </head> | ||
101 | + <body> | ||
102 | + <!-- Fixed navbar --> | ||
103 | + <div class="navbar navbar-default navbar-fixed-top" role="navigation"> | ||
104 | + <div class="container"> | ||
105 | + <div class="navbar-header"> | ||
106 | + <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> | ||
107 | + <span class="sr-only">Toggle navigation</span> | ||
108 | + <span class="icon-bar"></span> | ||
109 | + <span class="icon-bar"></span> | ||
110 | + <span class="icon-bar"></span> | ||
111 | + </button> | ||
112 | + <a class="navbar-brand" href="https://www.fastadmin.net" target="_blank">{$config.title}</a> | ||
113 | + </div> | ||
114 | + <div class="navbar-collapse collapse"> | ||
115 | + <form class="navbar-form navbar-right"> | ||
116 | + <div class="form-group"> | ||
117 | + Token: | ||
118 | + </div> | ||
119 | + <div class="form-group"> | ||
120 | + <input type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Tokentips}" placeholder="token" id="token" /> | ||
121 | + </div> | ||
122 | + <div class="form-group"> | ||
123 | + Apiurl: | ||
124 | + </div> | ||
125 | + <div class="form-group"> | ||
126 | + <input id="apiUrl" type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Apiurltips}" placeholder="https://api.mydomain.com" value="{$config.apiurl}" /> | ||
127 | + </div> | ||
128 | + <div class="form-group"> | ||
129 | + <button type="button" class="btn btn-success btn-sm" data-toggle="tooltip" title="{$lang.Savetips}" id="save_data"> | ||
130 | + <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> | ||
131 | + </button> | ||
132 | + </div> | ||
133 | + </form> | ||
134 | + </div><!--/.nav-collapse --> | ||
135 | + </div> | ||
136 | + </div> | ||
137 | + | ||
138 | + <div class="container"> | ||
139 | + <!-- menu --> | ||
140 | + <div id="sidebar"> | ||
141 | + <div class="list-group panel"> | ||
142 | + {foreach name="docslist" id="docs"} | ||
143 | + <a href="#{$key}" class="list-group-item" data-toggle="collapse" data-parent="#sidebar">{$key} <i class="fa fa-caret-down"></i></a> | ||
144 | + <div class="child collapse" id="{$key}"> | ||
145 | + {foreach name="docs" id="api" } | ||
146 | + <a href="javascript:;" data-id="{$api.id}" class="list-group-item">{$api.title}</a> | ||
147 | + {/foreach} | ||
148 | + </div> | ||
149 | + {/foreach} | ||
150 | + </div> | ||
151 | + </div> | ||
152 | + <div class="panel-group" id="accordion"> | ||
153 | + {foreach name="docslist" id="docs"} | ||
154 | + <h2>{$key}</h2> | ||
155 | + <hr> | ||
156 | + {foreach name="docs" id="api" } | ||
157 | + <div class="panel panel-default"> | ||
158 | + <div class="panel-heading" id="heading-{$api.id}"> | ||
159 | + <h4 class="panel-title"> | ||
160 | + <span class="label {$api.method_label}">{$api.method|strtoupper}</span> | ||
161 | + <a data-toggle="collapse" data-parent="#accordion{$api.id}" href="#collapseOne{$api.id}"> {$api.title} <span class="text-muted">{$api.route}</span></a> | ||
162 | + </h4> | ||
163 | + </div> | ||
164 | + <div id="collapseOne{$api.id}" class="panel-collapse collapse"> | ||
165 | + <div class="panel-body"> | ||
166 | + | ||
167 | + <!-- Nav tabs --> | ||
168 | + <ul class="nav nav-tabs" id="doctab{$api.id}"> | ||
169 | + <li class="active"><a href="#info{$api.id}" data-toggle="tab">{$lang.Info}</a></li> | ||
170 | + <li><a href="#sandbox{$api.id}" data-toggle="tab">{$lang.Sandbox}</a></li> | ||
171 | + <li><a href="#sample{$api.id}" data-toggle="tab">{$lang.Sampleoutput}</a></li> | ||
172 | + </ul> | ||
173 | + | ||
174 | + <!-- Tab panes --> | ||
175 | + <div class="tab-content"> | ||
176 | + | ||
177 | + <div class="tab-pane active" id="info{$api.id}"> | ||
178 | + <div class="well"> | ||
179 | + {$api.summary} | ||
180 | + </div> | ||
181 | + <div class="panel panel-default"> | ||
182 | + <div class="panel-heading"><strong>{$lang.Headers}</strong></div> | ||
183 | + <div class="panel-body"> | ||
184 | + {if $api.headerslist} | ||
185 | + <table class="table table-hover"> | ||
186 | + <thead> | ||
187 | + <tr> | ||
188 | + <th>{$lang.Name}</th> | ||
189 | + <th>{$lang.Type}</th> | ||
190 | + <th>{$lang.Required}</th> | ||
191 | + <th>{$lang.Description}</th> | ||
192 | + </tr> | ||
193 | + </thead> | ||
194 | + <tbody> | ||
195 | + {foreach name="api['headerslist']" id="header"} | ||
196 | + <tr> | ||
197 | + <td>{$header.name}</td> | ||
198 | + <td>{$header.type}</td> | ||
199 | + <td>{$header.required?'是':'否'}</td> | ||
200 | + <td>{$header.description}</td> | ||
201 | + </tr> | ||
202 | + {/foreach} | ||
203 | + </tbody> | ||
204 | + </table> | ||
205 | + {else /} | ||
206 | + 无 | ||
207 | + {/if} | ||
208 | + </div> | ||
209 | + </div> | ||
210 | + <div class="panel panel-default"> | ||
211 | + <div class="panel-heading"><strong>{$lang.Parameters}</strong></div> | ||
212 | + <div class="panel-body"> | ||
213 | + {if $api.paramslist} | ||
214 | + <table class="table table-hover"> | ||
215 | + <thead> | ||
216 | + <tr> | ||
217 | + <th>{$lang.Name}</th> | ||
218 | + <th>{$lang.Type}</th> | ||
219 | + <th>{$lang.Required}</th> | ||
220 | + <th>{$lang.Description}</th> | ||
221 | + </tr> | ||
222 | + </thead> | ||
223 | + <tbody> | ||
224 | + {foreach name="api['paramslist']" id="param"} | ||
225 | + <tr> | ||
226 | + <td>{$param.name}</td> | ||
227 | + <td>{$param.type}</td> | ||
228 | + <td>{:$param.required?'是':'否'}</td> | ||
229 | + <td>{$param.description}</td> | ||
230 | + </tr> | ||
231 | + {/foreach} | ||
232 | + </tbody> | ||
233 | + </table> | ||
234 | + {else /} | ||
235 | + 无 | ||
236 | + {/if} | ||
237 | + </div> | ||
238 | + </div> | ||
239 | + <div class="panel panel-default"> | ||
240 | + <div class="panel-heading"><strong>{$lang.Body}</strong></div> | ||
241 | + <div class="panel-body"> | ||
242 | + {$api.body|default='无'} | ||
243 | + </div> | ||
244 | + </div> | ||
245 | + </div><!-- #info --> | ||
246 | + | ||
247 | + <div class="tab-pane" id="sandbox{$api.id}"> | ||
248 | + <div class="row"> | ||
249 | + <div class="col-md-12"> | ||
250 | + {if $api.headerslist} | ||
251 | + <div class="panel panel-default"> | ||
252 | + <div class="panel-heading"><strong>{$lang.Headers}</strong></div> | ||
253 | + <div class="panel-body"> | ||
254 | + <div class="headers"> | ||
255 | + {foreach name="api['headerslist']" id="param"} | ||
256 | + <div class="form-group"> | ||
257 | + <label class="control-label" for="{$param.name}">{$param.name}</label> | ||
258 | + <input type="{$param.type}" class="form-control input-sm" id="{$param.name}" {if $param.required}required{/if} placeholder="{$param.description} - Ex: {$param.sample}" name="{$param.name}"> | ||
259 | + </div> | ||
260 | + {/foreach} | ||
261 | + </div> | ||
262 | + </div> | ||
263 | + </div> | ||
264 | + {/if} | ||
265 | + <div class="panel panel-default"> | ||
266 | + <div class="panel-heading"><strong>{$lang.Parameters}</strong></div> | ||
267 | + <div class="panel-body"> | ||
268 | + <form enctype="application/x-www-form-urlencoded" role="form" action="{$api.route}" method="{$api.method}" name="form{$api.id}" id="form{$api.id}"> | ||
269 | + {if $api.paramslist} | ||
270 | + {foreach name="api['paramslist']" id="param"} | ||
271 | + <div class="form-group"> | ||
272 | + <label class="control-label" for="{$param.name}">{$param.name}</label> | ||
273 | + <input type="{$param.type}" class="form-control input-sm" id="{$param.name}" {if $param.required}required{/if} placeholder="{$param.description}{if $param.sample} - 例: {$param.sample}{/if}" name="{$param.name}"> | ||
274 | + </div> | ||
275 | + {/foreach} | ||
276 | + {else /} | ||
277 | + <div class="form-group"> | ||
278 | + 无 | ||
279 | + </div> | ||
280 | + {/if} | ||
281 | + <div class="form-group"> | ||
282 | + <button type="submit" class="btn btn-success send" rel="{$api.id}">{$lang.Send}</button> | ||
283 | + <button type="reset" class="btn btn-info" rel="{$api.id}">{$lang.Reset}</button> | ||
284 | + </div> | ||
285 | + </form> | ||
286 | + </div> | ||
287 | + </div> | ||
288 | + <div class="panel panel-default"> | ||
289 | + <div class="panel-heading"><strong>{$lang.Response}</strong></div> | ||
290 | + <div class="panel-body"> | ||
291 | + <div class="row"> | ||
292 | + <div class="col-md-12" style="overflow-x:auto"> | ||
293 | + <pre id="response_headers{$api.id}"></pre> | ||
294 | + <pre id="response{$api.id}"></pre> | ||
295 | + </div> | ||
296 | + </div> | ||
297 | + </div> | ||
298 | + </div> | ||
299 | + <div class="panel panel-default"> | ||
300 | + <div class="panel-heading"><strong>{$lang.ReturnParameters}</strong></div> | ||
301 | + <div class="panel-body"> | ||
302 | + {if $api.returnparamslist} | ||
303 | + <table class="table table-hover"> | ||
304 | + <thead> | ||
305 | + <tr> | ||
306 | + <th>{$lang.Name}</th> | ||
307 | + <th>{$lang.Type}</th> | ||
308 | + <th>{$lang.Description}</th> | ||
309 | + </tr> | ||
310 | + </thead> | ||
311 | + <tbody> | ||
312 | + {foreach name="api['returnparamslist']" id="param"} | ||
313 | + <tr> | ||
314 | + <td>{$param.name}</td> | ||
315 | + <td>{$param.type}</td> | ||
316 | + <td>{$param.description}</td> | ||
317 | + </tr> | ||
318 | + {/foreach} | ||
319 | + </tbody> | ||
320 | + </table> | ||
321 | + {else /} | ||
322 | + 无 | ||
323 | + {/if} | ||
324 | + </div> | ||
325 | + </div> | ||
326 | + </div> | ||
327 | + </div> | ||
328 | + </div><!-- #sandbox --> | ||
329 | + | ||
330 | + <div class="tab-pane" id="sample{$api.id}"> | ||
331 | + <div class="row"> | ||
332 | + <div class="col-md-12"> | ||
333 | + <pre id="sample_response{$api.id}">{$api.return|default='无'}</pre> | ||
334 | + </div> | ||
335 | + </div> | ||
336 | + </div><!-- #sample --> | ||
337 | + | ||
338 | + </div><!-- .tab-content --> | ||
339 | + </div> | ||
340 | + </div> | ||
341 | + </div> | ||
342 | + {/foreach} | ||
343 | + {/foreach} | ||
344 | + </div> | ||
345 | + | ||
346 | + <hr> | ||
347 | + | ||
348 | + <div class="row mt0 footer"> | ||
349 | + <div class="col-md-6" align="left"> | ||
350 | + Generated on {:date('Y-m-d H:i:s')} | ||
351 | + </div> | ||
352 | + <div class="col-md-6" align="right"> | ||
353 | + <a href="https://www.fastadmin.net" target="_blank">FastAdmin</a> | ||
354 | + </div> | ||
355 | + </div> | ||
356 | + | ||
357 | + </div> <!-- /container --> | ||
358 | + | ||
359 | + <!-- jQuery --> | ||
360 | + <script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script> | ||
361 | + | ||
362 | + <!-- Bootstrap Core JavaScript --> | ||
363 | + <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> | ||
364 | + | ||
365 | + <script type="text/javascript"> | ||
366 | + function syntaxHighlight(json) { | ||
367 | + if (typeof json != 'string') { | ||
368 | + json = JSON.stringify(json, undefined, 2); | ||
369 | + } | ||
370 | + json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); | ||
371 | + return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { | ||
372 | + var cls = 'number'; | ||
373 | + if (/^"/.test(match)) { | ||
374 | + if (/:$/.test(match)) { | ||
375 | + cls = 'key'; | ||
376 | + } else { | ||
377 | + cls = 'string'; | ||
378 | + } | ||
379 | + } else if (/true|false/.test(match)) { | ||
380 | + cls = 'boolean'; | ||
381 | + } else if (/null/.test(match)) { | ||
382 | + cls = 'null'; | ||
383 | + } | ||
384 | + return '<span class="' + cls + '">' + match + '</span>'; | ||
385 | + }); | ||
386 | + } | ||
387 | + | ||
388 | + function prepareStr(str) { | ||
389 | + try { | ||
390 | + return syntaxHighlight(JSON.stringify(JSON.parse(str.replace(/'/g, '"')), null, 2)); | ||
391 | + } catch (e) { | ||
392 | + return str; | ||
393 | + } | ||
394 | + } | ||
395 | + var storage = (function () { | ||
396 | + var uid = new Date; | ||
397 | + var storage; | ||
398 | + var result; | ||
399 | + try { | ||
400 | + (storage = window.localStorage).setItem(uid, uid); | ||
401 | + result = storage.getItem(uid) == uid; | ||
402 | + storage.removeItem(uid); | ||
403 | + return result && storage; | ||
404 | + } catch (exception) { | ||
405 | + } | ||
406 | + }()); | ||
407 | + | ||
408 | + $.fn.serializeObject = function () | ||
409 | + { | ||
410 | + var o = {}; | ||
411 | + var a = this.serializeArray(); | ||
412 | + $.each(a, function () { | ||
413 | + if (!this.value) { | ||
414 | + return; | ||
415 | + } | ||
416 | + if (o[this.name] !== undefined) { | ||
417 | + if (!o[this.name].push) { | ||
418 | + o[this.name] = [o[this.name]]; | ||
419 | + } | ||
420 | + o[this.name].push(this.value || ''); | ||
421 | + } else { | ||
422 | + o[this.name] = this.value || ''; | ||
423 | + } | ||
424 | + }); | ||
425 | + return o; | ||
426 | + }; | ||
427 | + | ||
428 | + $(document).ready(function () { | ||
429 | + | ||
430 | + if (storage) { | ||
431 | + storage.getItem('token') && $('#token').val(storage.getItem('token')); | ||
432 | + storage.getItem('apiUrl') && $('#apiUrl').val(storage.getItem('apiUrl')); | ||
433 | + } | ||
434 | + | ||
435 | + $('[data-toggle="tooltip"]').tooltip({ | ||
436 | + placement: 'bottom' | ||
437 | + }); | ||
438 | + | ||
439 | + $(window).on("resize", function(){ | ||
440 | + $("#sidebar").css("max-height", $(window).height()-80); | ||
441 | + }); | ||
442 | + | ||
443 | + $(window).trigger("resize"); | ||
444 | + | ||
445 | + $(document).on("click", "#sidebar .list-group > .list-group-item", function(){ | ||
446 | + $("#sidebar .list-group > .list-group-item").removeClass("current"); | ||
447 | + $(this).addClass("current"); | ||
448 | + }); | ||
449 | + $(document).on("click", "#sidebar .child a", function(){ | ||
450 | + var heading = $("#heading-"+$(this).data("id")); | ||
451 | + if(!heading.next().hasClass("in")){ | ||
452 | + $("a", heading).trigger("click"); | ||
453 | + } | ||
454 | + $("html,body").animate({scrollTop:heading.offset().top-70}); | ||
455 | + }); | ||
456 | + | ||
457 | + $('code[id^=response]').hide(); | ||
458 | + | ||
459 | + $.each($('pre[id^=sample_response],pre[id^=sample_post_body]'), function () { | ||
460 | + if ($(this).html() == 'NA') { | ||
461 | + return; | ||
462 | + } | ||
463 | + var str = prepareStr($(this).html()); | ||
464 | + $(this).html(str); | ||
465 | + }); | ||
466 | + | ||
467 | + $("[data-toggle=popover]").popover({placement: 'right'}); | ||
468 | + | ||
469 | + $('[data-toggle=popover]').on('shown.bs.popover', function () { | ||
470 | + var $sample = $(this).parent().find(".popover-content"), | ||
471 | + str = $(this).data('content'); | ||
472 | + if (typeof str == "undefined" || str === "") { | ||
473 | + return; | ||
474 | + } | ||
475 | + var str = prepareStr(str); | ||
476 | + $sample.html('<pre>' + str + '</pre>'); | ||
477 | + }); | ||
478 | + | ||
479 | + $('body').on('click', '#save_data', function (e) { | ||
480 | + if (storage) { | ||
481 | + storage.setItem('token', $('#token').val()); | ||
482 | + storage.setItem('apiUrl', $('#apiUrl').val()); | ||
483 | + } else { | ||
484 | + alert('Your browser does not support local storage'); | ||
485 | + } | ||
486 | + }); | ||
487 | + | ||
488 | + $('body').on('click', '.send', function (e) { | ||
489 | + e.preventDefault(); | ||
490 | + var form = $(this).closest('form'); | ||
491 | + //added /g to get all the matched params instead of only first | ||
492 | + var matchedParamsInRoute = $(form).attr('action').match(/[^{]+(?=\})/g); | ||
493 | + var theId = $(this).attr('rel'); | ||
494 | + //keep a copy of action attribute in order to modify the copy | ||
495 | + //instead of the initial attribute | ||
496 | + var url = $(form).attr('action'); | ||
497 | + var method = $(form).prop('method').toLowerCase() || 'get'; | ||
498 | + | ||
499 | + var formData = new FormData(); | ||
500 | + | ||
501 | + $(form).find('input').each(function (i, input) { | ||
502 | + if ($(input).attr('type').toLowerCase() == 'file') { | ||
503 | + formData.append($(input).attr('name'), $(input)[0].files[0]); | ||
504 | + method = 'post'; | ||
505 | + } else { | ||
506 | + formData.append($(input).attr('name'), $(input).val()) | ||
507 | + } | ||
508 | + }); | ||
509 | + | ||
510 | + var index, key, value; | ||
511 | + | ||
512 | + if (matchedParamsInRoute) { | ||
513 | + var params = {}; | ||
514 | + formData.forEach(function(value, key){ | ||
515 | + params[key] = value; | ||
516 | + }); | ||
517 | + for (index = 0; index < matchedParamsInRoute.length; ++index) { | ||
518 | + try { | ||
519 | + key = matchedParamsInRoute[index]; | ||
520 | + value = params[key]; | ||
521 | + if (typeof value == "undefined") | ||
522 | + value = ""; | ||
523 | + url = url.replace("\{" + key + "\}", value); | ||
524 | + formData.delete(key); | ||
525 | + } catch (err) { | ||
526 | + console.log(err); | ||
527 | + } | ||
528 | + } | ||
529 | + } | ||
530 | + | ||
531 | + var headers = {}; | ||
532 | + | ||
533 | + var token = $('#token').val(); | ||
534 | + if (token.length > 0) { | ||
535 | + headers['token'] = token; | ||
536 | + } | ||
537 | + | ||
538 | + $("#sandbox" + theId + " .headers input[type=text]").each(function () { | ||
539 | + val = $(this).val(); | ||
540 | + if (val.length > 0) { | ||
541 | + headers[$(this).prop('name')] = val; | ||
542 | + } | ||
543 | + }); | ||
544 | + | ||
545 | + $.ajax({ | ||
546 | + url: $('#apiUrl').val() + url, | ||
547 | + data: method == 'get' ? $(form).serialize() : formData, | ||
548 | + type: method, | ||
549 | + dataType: 'json', | ||
550 | + contentType: false, | ||
551 | + processData: false, | ||
552 | + headers: headers, | ||
553 | + xhrFields: { | ||
554 | + withCredentials: true | ||
555 | + }, | ||
556 | + success: function (data, textStatus, xhr) { | ||
557 | + if (typeof data === 'object') { | ||
558 | + var str = JSON.stringify(data, null, 2); | ||
559 | + $('#response' + theId).html(syntaxHighlight(str)); | ||
560 | + } else { | ||
561 | + $('#response' + theId).html(data || ''); | ||
562 | + } | ||
563 | + $('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders()); | ||
564 | + $('#response' + theId).show(); | ||
565 | + }, | ||
566 | + error: function (xhr, textStatus, error) { | ||
567 | + try { | ||
568 | + var str = JSON.stringify($.parseJSON(xhr.responseText), null, 2); | ||
569 | + } catch (e) { | ||
570 | + var str = xhr.responseText; | ||
571 | + } | ||
572 | + $('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders()); | ||
573 | + $('#response' + theId).html(syntaxHighlight(str)); | ||
574 | + $('#response' + theId).show(); | ||
575 | + } | ||
576 | + }); | ||
577 | + return false; | ||
578 | + }); | ||
579 | + }); | ||
580 | + </script> | ||
581 | + </body> | ||
582 | +</html> |
application/admin/command/Crud.php
0 → 100644
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command; | ||
4 | + | ||
5 | +use fast\Form; | ||
6 | +use think\Config; | ||
7 | +use think\console\Command; | ||
8 | +use think\console\Input; | ||
9 | +use think\console\input\Option; | ||
10 | +use think\console\Output; | ||
11 | +use think\Db; | ||
12 | +use think\Exception; | ||
13 | +use think\exception\ErrorException; | ||
14 | +use think\Lang; | ||
15 | +use think\Loader; | ||
16 | + | ||
17 | +class Crud extends Command | ||
18 | +{ | ||
19 | + protected $stubList = []; | ||
20 | + | ||
21 | + protected $internalKeywords = [ | ||
22 | + 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor' | ||
23 | + ]; | ||
24 | + /** | ||
25 | + * Selectpage搜索字段关联 | ||
26 | + */ | ||
27 | + protected $fieldSelectpageMap = [ | ||
28 | + 'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids'] | ||
29 | + ]; | ||
30 | + | ||
31 | + /** | ||
32 | + * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表 | ||
33 | + */ | ||
34 | + protected $enumRadioSuffix = ['data', 'state', 'status']; | ||
35 | + | ||
36 | + /** | ||
37 | + * Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表 | ||
38 | + */ | ||
39 | + protected $setCheckboxSuffix = ['data', 'state', 'status']; | ||
40 | + | ||
41 | + /** | ||
42 | + * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框 | ||
43 | + */ | ||
44 | + protected $intDateSuffix = ['time']; | ||
45 | + | ||
46 | + /** | ||
47 | + * 开关后缀 | ||
48 | + */ | ||
49 | + protected $switchSuffix = ['switch']; | ||
50 | + | ||
51 | + /** | ||
52 | + * 富文本后缀 | ||
53 | + */ | ||
54 | + protected $editorSuffix = ['content']; | ||
55 | + | ||
56 | + /** | ||
57 | + * 城市后缀 | ||
58 | + */ | ||
59 | + protected $citySuffix = ['city']; | ||
60 | + | ||
61 | + /** | ||
62 | + * JSON后缀 | ||
63 | + */ | ||
64 | + protected $jsonSuffix = ['json']; | ||
65 | + | ||
66 | + /** | ||
67 | + * Selectpage对应的后缀 | ||
68 | + */ | ||
69 | + protected $selectpageSuffix = ['_id', '_ids']; | ||
70 | + | ||
71 | + /** | ||
72 | + * Selectpage多选对应的后缀 | ||
73 | + */ | ||
74 | + protected $selectpagesSuffix = ['_ids']; | ||
75 | + | ||
76 | + /** | ||
77 | + * 以指定字符结尾的字段格式化函数 | ||
78 | + */ | ||
79 | + protected $fieldFormatterSuffix = [ | ||
80 | + 'status' => ['type' => ['varchar', 'enum'], 'name' => 'status'], | ||
81 | + 'icon' => 'icon', | ||
82 | + 'flag' => 'flag', | ||
83 | + 'url' => 'url', | ||
84 | + 'image' => 'image', | ||
85 | + 'images' => 'images', | ||
86 | + 'avatar' => 'image', | ||
87 | + 'switch' => 'toggle', | ||
88 | + 'time' => ['type' => ['int', 'timestamp'], 'name' => 'datetime'] | ||
89 | + ]; | ||
90 | + | ||
91 | + /** | ||
92 | + * 识别为图片字段 | ||
93 | + */ | ||
94 | + protected $imageField = ['image', 'images', 'avatar', 'avatars']; | ||
95 | + | ||
96 | + /** | ||
97 | + * 识别为文件字段 | ||
98 | + */ | ||
99 | + protected $fileField = ['file', 'files']; | ||
100 | + | ||
101 | + /** | ||
102 | + * 保留字段 | ||
103 | + */ | ||
104 | + protected $reservedField = ['admin_id']; | ||
105 | + | ||
106 | + /** | ||
107 | + * 排除字段 | ||
108 | + */ | ||
109 | + protected $ignoreFields = []; | ||
110 | + | ||
111 | + /** | ||
112 | + * 排序字段 | ||
113 | + */ | ||
114 | + protected $sortField = 'weigh'; | ||
115 | + | ||
116 | + /** | ||
117 | + * 筛选字段 | ||
118 | + * @var string | ||
119 | + */ | ||
120 | + protected $headingFilterField = 'status'; | ||
121 | + | ||
122 | + /** | ||
123 | + * 添加时间字段 | ||
124 | + * @var string | ||
125 | + */ | ||
126 | + protected $createTimeField = 'createtime'; | ||
127 | + | ||
128 | + /** | ||
129 | + * 更新时间字段 | ||
130 | + * @var string | ||
131 | + */ | ||
132 | + protected $updateTimeField = 'updatetime'; | ||
133 | + | ||
134 | + /** | ||
135 | + * 软删除时间字段 | ||
136 | + * @var string | ||
137 | + */ | ||
138 | + protected $deleteTimeField = 'deletetime'; | ||
139 | + | ||
140 | + /** | ||
141 | + * 编辑器的Class | ||
142 | + */ | ||
143 | + protected $editorClass = 'editor'; | ||
144 | + | ||
145 | + /** | ||
146 | + * langList的key最长字节数 | ||
147 | + */ | ||
148 | + protected $fieldMaxLen = 0; | ||
149 | + | ||
150 | + protected function configure() | ||
151 | + { | ||
152 | + $this | ||
153 | + ->setName('crud') | ||
154 | + ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null) | ||
155 | + ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null) | ||
156 | + ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null) | ||
157 | + ->addOption('fields', 'i', Option::VALUE_OPTIONAL, 'model visible fields', null) | ||
158 | + ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override or force delete,without tips', null) | ||
159 | + ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1) | ||
160 | + ->addOption('relation', 'r', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table name without prefix', null) | ||
161 | + ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation model name', null) | ||
162 | + ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation foreign key', null) | ||
163 | + ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation primary key', null) | ||
164 | + ->addOption('relationfields', 's', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table fields', null) | ||
165 | + ->addOption('relationmode', 'o', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table mode,hasone or belongsto', null) | ||
166 | + ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null) | ||
167 | + ->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null) | ||
168 | + ->addOption('setcheckboxsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate checkbox component with suffix', null) | ||
169 | + ->addOption('enumradiosuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate radio component with suffix', null) | ||
170 | + ->addOption('imagefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate image component with suffix', null) | ||
171 | + ->addOption('filefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate file component with suffix', null) | ||
172 | + ->addOption('intdatesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate date component with suffix', null) | ||
173 | + ->addOption('switchsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate switch component with suffix', null) | ||
174 | + ->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null) | ||
175 | + ->addOption('jsonsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate fieldlist component with suffix', null) | ||
176 | + ->addOption('selectpagesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate selectpage component with suffix', null) | ||
177 | + ->addOption('selectpagessuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate multiple selectpage component with suffix', null) | ||
178 | + ->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null) | ||
179 | + ->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null) | ||
180 | + ->addOption('headingfilterfield', null, Option::VALUE_OPTIONAL, 'heading filter field', null) | ||
181 | + ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null) | ||
182 | + ->addOption('db', null, Option::VALUE_OPTIONAL, 'database config name', 'database') | ||
183 | + ->setDescription('Build CRUD controller and model from table'); | ||
184 | + } | ||
185 | + | ||
186 | + protected function execute(Input $input, Output $output) | ||
187 | + { | ||
188 | + $adminPath = dirname(__DIR__) . DS; | ||
189 | + //数据库 | ||
190 | + $db = $input->getOption('db'); | ||
191 | + //表名 | ||
192 | + $table = $input->getOption('table') ?: ''; | ||
193 | + //自定义控制器 | ||
194 | + $controller = $input->getOption('controller'); | ||
195 | + //自定义模型 | ||
196 | + $model = $input->getOption('model'); | ||
197 | + $model = $model ? $model : $controller; | ||
198 | + //验证器类 | ||
199 | + $validate = $model; | ||
200 | + //自定义显示字段 | ||
201 | + $fields = $input->getOption('fields'); | ||
202 | + //强制覆盖 | ||
203 | + $force = $input->getOption('force'); | ||
204 | + //是否为本地model,为0时表示为全局model将会把model放在app/common/model中 | ||
205 | + $local = $input->getOption('local'); | ||
206 | + if (!$table) { | ||
207 | + throw new Exception('table name can\'t empty'); | ||
208 | + } | ||
209 | + //是否生成菜单 | ||
210 | + $menu = $input->getOption("menu"); | ||
211 | + //关联表 | ||
212 | + $relation = $input->getOption('relation'); | ||
213 | + //自定义关联表模型 | ||
214 | + $relationModel = $input->getOption('relationmodel'); | ||
215 | + //模式 | ||
216 | + $relationMode = $mode = $input->getOption('relationmode'); | ||
217 | + //外键 | ||
218 | + $relationForeignKey = $input->getOption('relationforeignkey'); | ||
219 | + //主键 | ||
220 | + $relationPrimaryKey = $input->getOption('relationprimarykey'); | ||
221 | + //关联表显示字段 | ||
222 | + $relationFields = $input->getOption('relationfields'); | ||
223 | + //复选框后缀 | ||
224 | + $setcheckboxsuffix = $input->getOption('setcheckboxsuffix'); | ||
225 | + //单选框后缀 | ||
226 | + $enumradiosuffix = $input->getOption('enumradiosuffix'); | ||
227 | + //图片后缀 | ||
228 | + $imagefield = $input->getOption('imagefield'); | ||
229 | + //文件后缀 | ||
230 | + $filefield = $input->getOption('filefield'); | ||
231 | + //日期后缀 | ||
232 | + $intdatesuffix = $input->getOption('intdatesuffix'); | ||
233 | + //开关后缀 | ||
234 | + $switchsuffix = $input->getOption('switchsuffix'); | ||
235 | + //城市后缀 | ||
236 | + $citysuffix = $input->getOption('citysuffix'); | ||
237 | + //JSON配置后缀 | ||
238 | + $jsonsuffix = $input->getOption('jsonsuffix'); | ||
239 | + //selectpage后缀 | ||
240 | + $selectpagesuffix = $input->getOption('selectpagesuffix'); | ||
241 | + //selectpage多选后缀 | ||
242 | + $selectpagessuffix = $input->getOption('selectpagessuffix'); | ||
243 | + //排除字段 | ||
244 | + $ignoreFields = $input->getOption('ignorefields'); | ||
245 | + //排序字段 | ||
246 | + $sortfield = $input->getOption('sortfield'); | ||
247 | + //顶部筛选过滤字段 | ||
248 | + $headingfilterfield = $input->getOption('headingfilterfield'); | ||
249 | + //编辑器Class | ||
250 | + $editorclass = $input->getOption('editorclass'); | ||
251 | + if ($setcheckboxsuffix) { | ||
252 | + $this->setCheckboxSuffix = $setcheckboxsuffix; | ||
253 | + } | ||
254 | + if ($enumradiosuffix) { | ||
255 | + $this->enumRadioSuffix = $enumradiosuffix; | ||
256 | + } | ||
257 | + if ($imagefield) { | ||
258 | + $this->imageField = $imagefield; | ||
259 | + } | ||
260 | + if ($filefield) { | ||
261 | + $this->fileField = $filefield; | ||
262 | + } | ||
263 | + if ($intdatesuffix) { | ||
264 | + $this->intDateSuffix = $intdatesuffix; | ||
265 | + } | ||
266 | + if ($switchsuffix) { | ||
267 | + $this->switchSuffix = $switchsuffix; | ||
268 | + } | ||
269 | + if ($citysuffix) { | ||
270 | + $this->citySuffix = $citysuffix; | ||
271 | + } | ||
272 | + if ($jsonsuffix) { | ||
273 | + $this->jsonSuffix = $jsonsuffix; | ||
274 | + } | ||
275 | + if ($selectpagesuffix) { | ||
276 | + $this->selectpageSuffix = $selectpagesuffix; | ||
277 | + } | ||
278 | + if ($selectpagessuffix) { | ||
279 | + $this->selectpagesSuffix = $selectpagessuffix; | ||
280 | + } | ||
281 | + if ($ignoreFields) { | ||
282 | + $this->ignoreFields = $ignoreFields; | ||
283 | + } | ||
284 | + if ($editorclass) { | ||
285 | + $this->editorClass = $editorclass; | ||
286 | + } | ||
287 | + if ($sortfield) { | ||
288 | + $this->sortField = $sortfield; | ||
289 | + } | ||
290 | + if ($headingfilterfield) { | ||
291 | + $this->headingFilterField = $headingfilterfield; | ||
292 | + } | ||
293 | + | ||
294 | + $this->reservedField = array_merge($this->reservedField, [$this->createTimeField, $this->updateTimeField, $this->deleteTimeField]); | ||
295 | + | ||
296 | + $dbconnect = Db::connect($db); | ||
297 | + $dbname = Config::get($db . '.database'); | ||
298 | + $prefix = Config::get($db . '.prefix'); | ||
299 | + | ||
300 | + //模块 | ||
301 | + $moduleName = 'admin'; | ||
302 | + $modelModuleName = $local ? $moduleName : 'common'; | ||
303 | + $validateModuleName = $local ? $moduleName : 'common'; | ||
304 | + | ||
305 | + //检查主表 | ||
306 | + $modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table; | ||
307 | + $modelTableType = 'table'; | ||
308 | + $modelTableTypeName = $modelTableName = $modelName; | ||
309 | + $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true); | ||
310 | + if (!$modelTableInfo) { | ||
311 | + $modelTableType = 'name'; | ||
312 | + $modelTableName = $prefix . $modelName; | ||
313 | + $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true); | ||
314 | + if (!$modelTableInfo) { | ||
315 | + throw new Exception("table not found"); | ||
316 | + } | ||
317 | + } | ||
318 | + $modelTableInfo = $modelTableInfo[0]; | ||
319 | + | ||
320 | + $relations = []; | ||
321 | + //检查关联表 | ||
322 | + if ($relation) { | ||
323 | + $relationArr = $relation; | ||
324 | + $relations = []; | ||
325 | + | ||
326 | + foreach ($relationArr as $index => $relationTable) { | ||
327 | + $relationName = stripos($relationTable, $prefix) === 0 ? substr($relationTable, strlen($prefix)) : $relationTable; | ||
328 | + $relationTableType = 'table'; | ||
329 | + $relationTableTypeName = $relationTableName = $relationName; | ||
330 | + $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true); | ||
331 | + if (!$relationTableInfo) { | ||
332 | + $relationTableType = 'name'; | ||
333 | + $relationTableName = $prefix . $relationName; | ||
334 | + $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true); | ||
335 | + if (!$relationTableInfo) { | ||
336 | + throw new Exception("relation table not found"); | ||
337 | + } | ||
338 | + } | ||
339 | + $relationTableInfo = $relationTableInfo[0]; | ||
340 | + $relationModel = isset($relationModel[$index]) ? $relationModel[$index] : ''; | ||
341 | + | ||
342 | + list($relationNamespace, $relationName, $relationFile) = $this->getModelData($modelModuleName, $relationModel, $relationName); | ||
343 | + | ||
344 | + $relations[] = [ | ||
345 | + //关联表基础名 | ||
346 | + 'relationName' => $relationName, | ||
347 | + //关联表类命名空间 | ||
348 | + 'relationNamespace' => $relationNamespace, | ||
349 | + //关联模型名 | ||
350 | + 'relationModel' => $relationModel, | ||
351 | + //关联文件 | ||
352 | + 'relationFile' => $relationFile, | ||
353 | + //关联表名称 | ||
354 | + 'relationTableName' => $relationTableName, | ||
355 | + //关联表信息 | ||
356 | + 'relationTableInfo' => $relationTableInfo, | ||
357 | + //关联模型表类型(name或table) | ||
358 | + 'relationTableType' => $relationTableType, | ||
359 | + //关联模型表类型名称 | ||
360 | + 'relationTableTypeName' => $relationTableTypeName, | ||
361 | + //关联模式 | ||
362 | + 'relationFields' => isset($relationFields[$index]) ? explode(',', $relationFields[$index]) : [], | ||
363 | + //关联模式 | ||
364 | + 'relationMode' => isset($relationMode[$index]) ? $relationMode[$index] : 'belongsto', | ||
365 | + //关联表外键 | ||
366 | + 'relationForeignKey' => isset($relationForeignKey[$index]) ? $relationForeignKey[$index] : Loader::parseName($relationName) . '_id', | ||
367 | + //关联表主键 | ||
368 | + 'relationPrimaryKey' => isset($relationPrimaryKey[$index]) ? $relationPrimaryKey[$index] : '', | ||
369 | + ]; | ||
370 | + } | ||
371 | + } | ||
372 | + | ||
373 | + //根据表名匹配对应的Fontawesome图标 | ||
374 | + $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less'); | ||
375 | + $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o'; | ||
376 | + | ||
377 | + //控制器 | ||
378 | + list($controllerNamespace, $controllerName, $controllerFile, $controllerArr) = $this->getControllerData($moduleName, $controller, $table); | ||
379 | + //模型 | ||
380 | + list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($modelModuleName, $model, $table); | ||
381 | + //验证器 | ||
382 | + list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($validateModuleName, $validate, $table); | ||
383 | + | ||
384 | + //处理基础文件名,取消所有下划线并转换为小写 | ||
385 | + $baseNameArr = $controllerArr; | ||
386 | + $baseFileName = Loader::parseName(array_pop($baseNameArr), 0); | ||
387 | + array_push($baseNameArr, $baseFileName); | ||
388 | + $controllerBaseName = strtolower(implode(DS, $baseNameArr)); | ||
389 | + $controllerUrl = strtolower(implode('/', $baseNameArr)); | ||
390 | + | ||
391 | + //视图文件 | ||
392 | + $viewArr = $controllerArr; | ||
393 | + $lastValue = array_pop($viewArr); | ||
394 | + $viewArr[] = Loader::parseName($lastValue, 0); | ||
395 | + array_unshift($viewArr, 'view'); | ||
396 | + $viewDir = $adminPath . strtolower(implode(DS, $viewArr)) . DS; | ||
397 | + | ||
398 | + //最终将生成的文件路径 | ||
399 | + $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerBaseName . '.js'; | ||
400 | + $addFile = $viewDir . 'add.html'; | ||
401 | + $editFile = $viewDir . 'edit.html'; | ||
402 | + $indexFile = $viewDir . 'index.html'; | ||
403 | + $recyclebinFile = $viewDir . 'recyclebin.html'; | ||
404 | + $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerBaseName . '.php'; | ||
405 | + | ||
406 | + //是否为删除模式 | ||
407 | + $delete = $input->getOption('delete'); | ||
408 | + if ($delete) { | ||
409 | + $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $recyclebinFile, $langFile, $javascriptFile]; | ||
410 | + foreach ($readyFiles as $k => $v) { | ||
411 | + $output->warning($v); | ||
412 | + } | ||
413 | + if (!$force) { | ||
414 | + $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: "); | ||
415 | + $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r')); | ||
416 | + if (trim($line) != 'yes') { | ||
417 | + throw new Exception("Operation is aborted!"); | ||
418 | + } | ||
419 | + } | ||
420 | + foreach ($readyFiles as $k => $v) { | ||
421 | + if (file_exists($v)) { | ||
422 | + unlink($v); | ||
423 | + } | ||
424 | + //删除空文件夹 | ||
425 | + switch ($v) { | ||
426 | + case $modelFile: | ||
427 | + $this->removeEmptyBaseDir($v, $modelArr); | ||
428 | + break; | ||
429 | + case $validateFile: | ||
430 | + $this->removeEmptyBaseDir($v, $validateArr); | ||
431 | + break; | ||
432 | + case $addFile: | ||
433 | + case $editFile: | ||
434 | + case $indexFile: | ||
435 | + case $recyclebinFile: | ||
436 | + $this->removeEmptyBaseDir($v, $viewArr); | ||
437 | + break; | ||
438 | + default: | ||
439 | + $this->removeEmptyBaseDir($v, $controllerArr); | ||
440 | + } | ||
441 | + } | ||
442 | + | ||
443 | + $output->info("Delete Successed"); | ||
444 | + return; | ||
445 | + } | ||
446 | + | ||
447 | + //非覆盖模式时如果存在控制器文件则报错 | ||
448 | + if (is_file($controllerFile) && !$force) { | ||
449 | + throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true "); | ||
450 | + } | ||
451 | + | ||
452 | + //非覆盖模式时如果存在模型文件则报错 | ||
453 | + if (is_file($modelFile) && !$force) { | ||
454 | + throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true "); | ||
455 | + } | ||
456 | + | ||
457 | + //非覆盖模式时如果存在验证文件则报错 | ||
458 | + if (is_file($validateFile) && !$force) { | ||
459 | + throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true "); | ||
460 | + } | ||
461 | + | ||
462 | + require $adminPath . 'common.php'; | ||
463 | + | ||
464 | + //从数据库中获取表字段信息 | ||
465 | + $sql = "SELECT * FROM `information_schema`.`columns` " | ||
466 | + . "WHERE TABLE_SCHEMA = ? AND table_name = ? " | ||
467 | + . "ORDER BY ORDINAL_POSITION"; | ||
468 | + //加载主表的列 | ||
469 | + $columnList = $dbconnect->query($sql, [$dbname, $modelTableName]); | ||
470 | + $fieldArr = []; | ||
471 | + foreach ($columnList as $k => $v) { | ||
472 | + $fieldArr[] = $v['COLUMN_NAME']; | ||
473 | + } | ||
474 | + | ||
475 | + // 加载关联表的列 | ||
476 | + foreach ($relations as $index => &$relation) { | ||
477 | + $relationColumnList = $dbconnect->query($sql, [$dbname, $relation['relationTableName']]); | ||
478 | + | ||
479 | + $relationFieldList = []; | ||
480 | + foreach ($relationColumnList as $k => $v) { | ||
481 | + $relationFieldList[] = $v['COLUMN_NAME']; | ||
482 | + } | ||
483 | + if (!$relation['relationPrimaryKey']) { | ||
484 | + foreach ($relationColumnList as $k => $v) { | ||
485 | + if ($v['COLUMN_KEY'] == 'PRI') { | ||
486 | + $relation['relationPrimaryKey'] = $v['COLUMN_NAME']; | ||
487 | + break; | ||
488 | + } | ||
489 | + } | ||
490 | + } | ||
491 | + // 如果主键为空 | ||
492 | + if (!$relation['relationPrimaryKey']) { | ||
493 | + throw new Exception('Relation Primary key not found!'); | ||
494 | + } | ||
495 | + // 如果主键不在表字段中 | ||
496 | + if (!in_array($relation['relationPrimaryKey'], $relationFieldList)) { | ||
497 | + throw new Exception('Relation Primary key not found in table!'); | ||
498 | + } | ||
499 | + $relation['relationColumnList'] = $relationColumnList; | ||
500 | + $relation['relationFieldList'] = $relationFieldList; | ||
501 | + } | ||
502 | + unset($relation); | ||
503 | + | ||
504 | + $addList = []; | ||
505 | + $editList = []; | ||
506 | + $javascriptList = []; | ||
507 | + $langList = []; | ||
508 | + $field = 'id'; | ||
509 | + $order = 'id'; | ||
510 | + $priDefined = false; | ||
511 | + $priKey = ''; | ||
512 | + $relationPrimaryKey = ''; | ||
513 | + foreach ($columnList as $k => $v) { | ||
514 | + if ($v['COLUMN_KEY'] == 'PRI') { | ||
515 | + $priKey = $v['COLUMN_NAME']; | ||
516 | + break; | ||
517 | + } | ||
518 | + } | ||
519 | + if (!$priKey) { | ||
520 | + throw new Exception('Primary key not found!'); | ||
521 | + } | ||
522 | + | ||
523 | + $order = $priKey; | ||
524 | + | ||
525 | + //如果是关联模型 | ||
526 | + foreach ($relations as $index => &$relation) { | ||
527 | + if ($relation['relationMode'] == 'hasone') { | ||
528 | + $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id"; | ||
529 | + $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey; | ||
530 | + | ||
531 | + if (!in_array($relationForeignKey, $relation['relationFieldList'])) { | ||
532 | + throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']'); | ||
533 | + } | ||
534 | + if (!in_array($relationPrimaryKey, $fieldArr)) { | ||
535 | + throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']'); | ||
536 | + } | ||
537 | + } else { | ||
538 | + $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id"; | ||
539 | + $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey']; | ||
540 | + if (!in_array($relationForeignKey, $fieldArr)) { | ||
541 | + throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']'); | ||
542 | + } | ||
543 | + if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) { | ||
544 | + throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']'); | ||
545 | + } | ||
546 | + } | ||
547 | + $relation['relationForeignKey'] = $relationForeignKey; | ||
548 | + $relation['relationPrimaryKey'] = $relationPrimaryKey; | ||
549 | + $relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName']; | ||
550 | + } | ||
551 | + unset($relation); | ||
552 | + | ||
553 | + try { | ||
554 | + Form::setEscapeHtml(false); | ||
555 | + $setAttrArr = []; | ||
556 | + $getAttrArr = []; | ||
557 | + $getEnumArr = []; | ||
558 | + $appendAttrList = []; | ||
559 | + $controllerAssignList = []; | ||
560 | + $headingHtml = '{:build_heading()}'; | ||
561 | + $recyclebinHtml = ''; | ||
562 | + | ||
563 | + //循环所有字段,开始构造视图的HTML和JS信息 | ||
564 | + foreach ($columnList as $k => $v) { | ||
565 | + $field = $v['COLUMN_NAME']; | ||
566 | + $itemArr = []; | ||
567 | + // 这里构建Enum和Set类型的列表数据 | ||
568 | + if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) { | ||
569 | + if ($v['DATA_TYPE'] !== 'tinyint') { | ||
570 | + $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1); | ||
571 | + $itemArr = explode(',', str_replace("'", '', $itemArr)); | ||
572 | + } | ||
573 | + $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']); | ||
574 | + //如果类型为tinyint且有使用备注数据 | ||
575 | + if ($itemArr && $v['DATA_TYPE'] == 'tinyint') { | ||
576 | + $v['DATA_TYPE'] = 'enum'; | ||
577 | + } | ||
578 | + } | ||
579 | + // 语言列表 | ||
580 | + if ($v['COLUMN_COMMENT'] != '') { | ||
581 | + $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']); | ||
582 | + } | ||
583 | + $inputType = ''; | ||
584 | + //保留字段不能修改和添加 | ||
585 | + if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) { | ||
586 | + $inputType = $this->getFieldType($v); | ||
587 | + | ||
588 | + // 如果是number类型时增加一个步长 | ||
589 | + $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0; | ||
590 | + | ||
591 | + $attrArr = ['id' => "c-{$field}"]; | ||
592 | + $cssClassArr = ['form-control']; | ||
593 | + $fieldName = "row[{$field}]"; | ||
594 | + $defaultValue = $v['COLUMN_DEFAULT']; | ||
595 | + $editValue = "{\$row.{$field}|htmlentities}"; | ||
596 | + // 如果默认值非null,则是一个必选项 | ||
597 | + if ($v['IS_NULLABLE'] == 'NO') { | ||
598 | + $attrArr['data-rule'] = 'required'; | ||
599 | + } | ||
600 | + | ||
601 | + if ($inputType == 'select') { | ||
602 | + $cssClassArr[] = 'selectpicker'; | ||
603 | + $attrArr['class'] = implode(' ', $cssClassArr); | ||
604 | + if ($v['DATA_TYPE'] == 'set') { | ||
605 | + $attrArr['multiple'] = ''; | ||
606 | + $fieldName .= "[]"; | ||
607 | + } | ||
608 | + $attrArr['name'] = $fieldName; | ||
609 | + | ||
610 | + $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select'); | ||
611 | + | ||
612 | + $itemArr = $this->getLangArray($itemArr, false); | ||
613 | + //添加一个获取器 | ||
614 | + $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select'); | ||
615 | + if ($v['DATA_TYPE'] == 'set') { | ||
616 | + $this->setAttr($setAttrArr, $field, $inputType); | ||
617 | + } | ||
618 | + $this->appendAttr($appendAttrList, $field); | ||
619 | + $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]); | ||
620 | + $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]); | ||
621 | + } elseif ($inputType == 'datetime') { | ||
622 | + $cssClassArr[] = 'datetimepicker'; | ||
623 | + $attrArr['class'] = implode(' ', $cssClassArr); | ||
624 | + $format = "YYYY-MM-DD HH:mm:ss"; | ||
625 | + $phpFormat = "Y-m-d H:i:s"; | ||
626 | + $fieldFunc = ''; | ||
627 | + switch ($v['DATA_TYPE']) { | ||
628 | + case 'year': | ||
629 | + $format = "YYYY"; | ||
630 | + $phpFormat = 'Y'; | ||
631 | + break; | ||
632 | + case 'date': | ||
633 | + $format = "YYYY-MM-DD"; | ||
634 | + $phpFormat = 'Y-m-d'; | ||
635 | + break; | ||
636 | + case 'time': | ||
637 | + $format = "HH:mm:ss"; | ||
638 | + $phpFormat = 'H:i:s'; | ||
639 | + break; | ||
640 | + case 'timestamp': | ||
641 | + $fieldFunc = 'datetime'; | ||
642 | + // no break | ||
643 | + case 'datetime': | ||
644 | + $format = "YYYY-MM-DD HH:mm:ss"; | ||
645 | + $phpFormat = 'Y-m-d H:i:s'; | ||
646 | + break; | ||
647 | + default: | ||
648 | + $fieldFunc = 'datetime'; | ||
649 | + $this->getAttr($getAttrArr, $field, $inputType); | ||
650 | + $this->setAttr($setAttrArr, $field, $inputType); | ||
651 | + $this->appendAttr($appendAttrList, $field); | ||
652 | + break; | ||
653 | + } | ||
654 | + $defaultDateTime = "{:date('{$phpFormat}')}"; | ||
655 | + $attrArr['data-date-format'] = $format; | ||
656 | + $attrArr['data-use-current'] = "true"; | ||
657 | + $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr); | ||
658 | + $formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr); | ||
659 | + } elseif ($inputType == 'checkbox' || $inputType == 'radio') { | ||
660 | + unset($attrArr['data-rule']); | ||
661 | + $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName; | ||
662 | + $attrArr['name'] = "row[{$fieldName}]"; | ||
663 | + | ||
664 | + $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType); | ||
665 | + $itemArr = $this->getLangArray($itemArr, false); | ||
666 | + //添加一个获取器 | ||
667 | + $this->getAttr($getAttrArr, $field, $inputType); | ||
668 | + if ($inputType == 'checkbox') { | ||
669 | + $this->setAttr($setAttrArr, $field, $inputType); | ||
670 | + } | ||
671 | + $this->appendAttr($appendAttrList, $field); | ||
672 | + $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue; | ||
673 | + | ||
674 | + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]); | ||
675 | + $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]); | ||
676 | + } elseif ($inputType == 'textarea') { | ||
677 | + $cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : ''; | ||
678 | + $attrArr['class'] = implode(' ', $cssClassArr); | ||
679 | + $attrArr['rows'] = 5; | ||
680 | + $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr); | ||
681 | + $formEditElement = Form::textarea($fieldName, $editValue, $attrArr); | ||
682 | + } elseif ($inputType == 'switch') { | ||
683 | + unset($attrArr['data-rule']); | ||
684 | + if ($defaultValue === '1' || $defaultValue === 'Y') { | ||
685 | + $yes = $defaultValue; | ||
686 | + $no = $defaultValue === '1' ? '0' : 'N'; | ||
687 | + } else { | ||
688 | + $no = $defaultValue; | ||
689 | + $yes = $defaultValue === '0' ? '1' : 'Y'; | ||
690 | + } | ||
691 | + if (!$itemArr) { | ||
692 | + $itemArr = [$yes => 'Yes', $no => 'No']; | ||
693 | + } | ||
694 | + $stateNoClass = 'fa-flip-horizontal text-gray'; | ||
695 | + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']); | ||
696 | + $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => "{\$row.{$field}}", 'fieldSwitchClass' => "{eq name=\"\$row.{$field}\" value=\"{$no}\"}fa-flip-horizontal text-gray{/eq}"]); | ||
697 | + } elseif ($inputType == 'citypicker') { | ||
698 | + $attrArr['class'] = implode(' ', $cssClassArr); | ||
699 | + $attrArr['data-toggle'] = "city-picker"; | ||
700 | + $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr)); | ||
701 | + $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr)); | ||
702 | + } elseif ($inputType == 'fieldlist') { | ||
703 | + $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']); | ||
704 | + $itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key'; | ||
705 | + $itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value'; | ||
706 | + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $defaultValue]); | ||
707 | + $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $editValue]); | ||
708 | + } else { | ||
709 | + $search = $replace = ''; | ||
710 | + //特殊字段为关联搜索 | ||
711 | + if ($this->isMatchSuffix($field, $this->selectpageSuffix)) { | ||
712 | + $inputType = 'text'; | ||
713 | + $defaultValue = ''; | ||
714 | + $attrArr['data-rule'] = 'required'; | ||
715 | + $cssClassArr[] = 'selectpage'; | ||
716 | + $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_'))); | ||
717 | + $attrArr['data-source'] = $selectpageController . "/index"; | ||
718 | + //如果是类型表需要特殊处理下 | ||
719 | + if ($selectpageController == 'category') { | ||
720 | + $attrArr['data-source'] = 'category/selectpage'; | ||
721 | + $attrArr['data-params'] = '##replacetext##'; | ||
722 | + $search = '"##replacetext##"'; | ||
723 | + $replace = '\'{"custom[type]":"' . $table . '"}\''; | ||
724 | + } elseif ($selectpageController == 'admin') { | ||
725 | + $attrArr['data-source'] = 'auth/admin/selectpage'; | ||
726 | + } elseif ($selectpageController == 'user') { | ||
727 | + $attrArr['data-source'] = 'user/user/index'; | ||
728 | + } | ||
729 | + if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) { | ||
730 | + $attrArr['data-multiple'] = 'true'; | ||
731 | + } | ||
732 | + foreach ($this->fieldSelectpageMap as $m => $n) { | ||
733 | + if (in_array($field, $n)) { | ||
734 | + $attrArr['data-field'] = $m; | ||
735 | + break; | ||
736 | + } | ||
737 | + } | ||
738 | + } | ||
739 | + //因为有自动完成可输入其它内容 | ||
740 | + $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step; | ||
741 | + $attrArr['class'] = implode(' ', $cssClassArr); | ||
742 | + $isUpload = false; | ||
743 | + if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) { | ||
744 | + $isUpload = true; | ||
745 | + } | ||
746 | + //如果是步长则加上步长 | ||
747 | + if ($step) { | ||
748 | + $attrArr['step'] = $step; | ||
749 | + } | ||
750 | + //如果是图片加上个size | ||
751 | + if ($isUpload) { | ||
752 | + $attrArr['size'] = 50; | ||
753 | + } | ||
754 | + | ||
755 | + $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr); | ||
756 | + $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr); | ||
757 | + if ($search && $replace) { | ||
758 | + $formAddElement = str_replace($search, $replace, $formAddElement); | ||
759 | + $formEditElement = str_replace($search, $replace, $formEditElement); | ||
760 | + } | ||
761 | + //如果是图片或文件 | ||
762 | + if ($isUpload) { | ||
763 | + $formAddElement = $this->getImageUpload($field, $formAddElement); | ||
764 | + $formEditElement = $this->getImageUpload($field, $formEditElement); | ||
765 | + } | ||
766 | + } | ||
767 | + //构造添加和编辑HTML信息 | ||
768 | + $addList[] = $this->getFormGroup($field, $formAddElement); | ||
769 | + $editList[] = $this->getFormGroup($field, $formEditElement); | ||
770 | + } | ||
771 | + | ||
772 | + //过滤text类型字段 | ||
773 | + if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') { | ||
774 | + //主键 | ||
775 | + if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) { | ||
776 | + $priDefined = true; | ||
777 | + $javascriptList[] = "{checkbox: true}"; | ||
778 | + } | ||
779 | + if ($this->deleteTimeField == $field) { | ||
780 | + $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]); | ||
781 | + continue; | ||
782 | + } | ||
783 | + if (!$fields || in_array($field, explode(',', $fields))) { | ||
784 | + //构造JS列信息 | ||
785 | + $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr); | ||
786 | + } | ||
787 | + if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) { | ||
788 | + $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]); | ||
789 | + } | ||
790 | + //排序方式,如果有指定排序字段,否则按主键排序 | ||
791 | + $order = $field == $this->sortField ? $this->sortField : $order; | ||
792 | + } | ||
793 | + } | ||
794 | + | ||
795 | + //循环关联表,追加语言包和JS列 | ||
796 | + foreach ($relations as $index => $relation) { | ||
797 | + foreach ($relation['relationColumnList'] as $k => $v) { | ||
798 | + // 不显示的字段直接过滤掉 | ||
799 | + if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) { | ||
800 | + continue; | ||
801 | + } | ||
802 | + | ||
803 | + $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME']; | ||
804 | + // 语言列表 | ||
805 | + if ($v['COLUMN_COMMENT'] != '') { | ||
806 | + $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']); | ||
807 | + } | ||
808 | + | ||
809 | + //过滤text类型字段 | ||
810 | + if ($v['DATA_TYPE'] != 'text') { | ||
811 | + //构造JS列信息 | ||
812 | + $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']); | ||
813 | + } | ||
814 | + } | ||
815 | + } | ||
816 | + | ||
817 | + //JS最后一列加上操作列 | ||
818 | + $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}"; | ||
819 | + $addList = implode("\n", array_filter($addList)); | ||
820 | + $editList = implode("\n", array_filter($editList)); | ||
821 | + $javascriptList = implode(",\n", array_filter($javascriptList)); | ||
822 | + $langList = implode(",\n", array_filter($langList)); | ||
823 | + //数组等号对齐 | ||
824 | + $langList = array_filter(explode(",\n", $langList . ",\n")); | ||
825 | + foreach ($langList as &$line) { | ||
826 | + if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) { | ||
827 | + $line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'"; | ||
828 | + } | ||
829 | + } | ||
830 | + unset($line); | ||
831 | + $langList = implode(",\n", array_filter($langList)); | ||
832 | + | ||
833 | + //表注释 | ||
834 | + $tableComment = $modelTableInfo['Comment']; | ||
835 | + $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment; | ||
836 | + | ||
837 | + $modelInit = ''; | ||
838 | + if ($priKey != $order) { | ||
839 | + $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]); | ||
840 | + } | ||
841 | + | ||
842 | + $data = [ | ||
843 | + 'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';", | ||
844 | + 'controllerNamespace' => $controllerNamespace, | ||
845 | + 'modelNamespace' => $modelNamespace, | ||
846 | + 'validateNamespace' => $validateNamespace, | ||
847 | + 'controllerUrl' => $controllerUrl, | ||
848 | + 'controllerName' => $controllerName, | ||
849 | + 'controllerAssignList' => implode("\n", $controllerAssignList), | ||
850 | + 'modelName' => $modelName, | ||
851 | + 'modelTableName' => $modelTableName, | ||
852 | + 'modelTableType' => $modelTableType, | ||
853 | + 'modelTableTypeName' => $modelTableTypeName, | ||
854 | + 'validateName' => $validateName, | ||
855 | + 'tableComment' => $tableComment, | ||
856 | + 'iconName' => $iconName, | ||
857 | + 'pk' => $priKey, | ||
858 | + 'order' => $order, | ||
859 | + 'table' => $table, | ||
860 | + 'tableName' => $modelTableName, | ||
861 | + 'addList' => $addList, | ||
862 | + 'editList' => $editList, | ||
863 | + 'javascriptList' => $javascriptList, | ||
864 | + 'langList' => $langList, | ||
865 | + 'sofeDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '', | ||
866 | + 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '', | ||
867 | + 'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false', | ||
868 | + 'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false', | ||
869 | + 'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false', | ||
870 | + 'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false', | ||
871 | + 'relationSearch' => $relations ? 'true' : 'false', | ||
872 | + 'relationWithList' => '', | ||
873 | + 'relationMethodList' => '', | ||
874 | + 'controllerIndex' => '', | ||
875 | + 'recyclebinJs' => '', | ||
876 | + 'headingHtml' => $headingHtml, | ||
877 | + 'recyclebinHtml' => $recyclebinHtml, | ||
878 | + 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '', | ||
879 | + 'appendAttrList' => implode(",\n", $appendAttrList), | ||
880 | + 'getEnumList' => implode("\n\n", $getEnumArr), | ||
881 | + 'getAttrList' => implode("\n\n", $getAttrArr), | ||
882 | + 'setAttrList' => implode("\n\n", $setAttrArr), | ||
883 | + 'modelInit' => $modelInit, | ||
884 | + ]; | ||
885 | + | ||
886 | + //如果使用关联模型 | ||
887 | + if ($relations) { | ||
888 | + $relationWithList = $relationMethodList = $relationVisibleFieldList = []; | ||
889 | + foreach ($relations as $index => $relation) { | ||
890 | + //需要构造关联的方法 | ||
891 | + $relation['relationMethod'] = strtolower($relation['relationName']); | ||
892 | + | ||
893 | + //关联的模式 | ||
894 | + $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo'; | ||
895 | + | ||
896 | + //关联字段 | ||
897 | + $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey; | ||
898 | + | ||
899 | + //预载入的方法 | ||
900 | + $relationWithList[] = $relation['relationMethod']; | ||
901 | + | ||
902 | + unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']); | ||
903 | + | ||
904 | + //构造关联模型的方法 | ||
905 | + $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation); | ||
906 | + | ||
907 | + //如果设置了显示主表字段,则必须显式将关联表字段显示 | ||
908 | + if ($fields) { | ||
909 | + $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);"; | ||
910 | + } | ||
911 | + | ||
912 | + //显示的字段 | ||
913 | + if ($relation['relationFields']) { | ||
914 | + $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);"; | ||
915 | + } | ||
916 | + } | ||
917 | + | ||
918 | + $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])"; | ||
919 | + $data['relationMethodList'] = implode("\n\n", $relationMethodList); | ||
920 | + $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList); | ||
921 | + | ||
922 | + //需要重写index方法 | ||
923 | + $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data); | ||
924 | + } elseif ($fields) { | ||
925 | + $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']); | ||
926 | + //需要重写index方法 | ||
927 | + $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data); | ||
928 | + } | ||
929 | + | ||
930 | + // 生成控制器文件 | ||
931 | + $this->writeToFile('controller', $data, $controllerFile); | ||
932 | + // 生成模型文件 | ||
933 | + $this->writeToFile('model', $data, $modelFile); | ||
934 | + | ||
935 | + if ($relations) { | ||
936 | + foreach ($relations as $i => $relation) { | ||
937 | + $relation['modelNamespace'] = $data['modelNamespace']; | ||
938 | + if (!is_file($relation['relationFile'])) { | ||
939 | + // 生成关联模型文件 | ||
940 | + $this->writeToFile('relationmodel', $relation, $relation['relationFile']); | ||
941 | + } | ||
942 | + } | ||
943 | + } | ||
944 | + // 生成验证文件 | ||
945 | + $this->writeToFile('validate', $data, $validateFile); | ||
946 | + // 生成视图文件 | ||
947 | + $this->writeToFile('add', $data, $addFile); | ||
948 | + $this->writeToFile('edit', $data, $editFile); | ||
949 | + $this->writeToFile('index', $data, $indexFile); | ||
950 | + if ($recyclebinHtml) { | ||
951 | + $this->writeToFile('recyclebin', $data, $recyclebinFile); | ||
952 | + $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : ''); | ||
953 | + $recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : ''; | ||
954 | + $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]); | ||
955 | + } | ||
956 | + // 生成JS文件 | ||
957 | + $this->writeToFile('javascript', $data, $javascriptFile); | ||
958 | + // 生成语言文件 | ||
959 | + $this->writeToFile('lang', $data, $langFile); | ||
960 | + } catch (ErrorException $e) { | ||
961 | + throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile()); | ||
962 | + } | ||
963 | + | ||
964 | + //继续生成菜单 | ||
965 | + if ($menu) { | ||
966 | + exec("php think menu -c {$controllerUrl}"); | ||
967 | + } | ||
968 | + | ||
969 | + $output->info("Build Successed"); | ||
970 | + } | ||
971 | + | ||
972 | + protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '') | ||
973 | + { | ||
974 | + if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) { | ||
975 | + return; | ||
976 | + } | ||
977 | + $fieldList = $this->getFieldListName($field); | ||
978 | + $methodName = 'get' . ucfirst($fieldList); | ||
979 | + foreach ($itemArr as $k => &$v) { | ||
980 | + $v = "__('" . mb_ucfirst($v) . "')"; | ||
981 | + } | ||
982 | + unset($v); | ||
983 | + $itemString = $this->getArrayString($itemArr); | ||
984 | + $getEnum[] = <<<EOD | ||
985 | + public function {$methodName}() | ||
986 | + { | ||
987 | + return [{$itemString}]; | ||
988 | + } | ||
989 | +EOD; | ||
990 | + $controllerAssignList[] = <<<EOD | ||
991 | + \$this->view->assign("{$fieldList}", \$this->model->{$methodName}()); | ||
992 | +EOD; | ||
993 | + } | ||
994 | + | ||
995 | + protected function getAttr(&$getAttr, $field, $inputType = '') | ||
996 | + { | ||
997 | + if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) { | ||
998 | + return; | ||
999 | + } | ||
1000 | + $attrField = ucfirst($this->getCamelizeName($field)); | ||
1001 | + $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]); | ||
1002 | + } | ||
1003 | + | ||
1004 | + protected function setAttr(&$setAttr, $field, $inputType = '') | ||
1005 | + { | ||
1006 | + if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) { | ||
1007 | + return; | ||
1008 | + } | ||
1009 | + $attrField = ucfirst($this->getCamelizeName($field)); | ||
1010 | + if ($inputType == 'datetime') { | ||
1011 | + $return = <<<EOD | ||
1012 | +return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value); | ||
1013 | +EOD; | ||
1014 | + } elseif (in_array($inputType, ['checkbox', 'select'])) { | ||
1015 | + $return = <<<EOD | ||
1016 | +return is_array(\$value) ? implode(',', \$value) : \$value; | ||
1017 | +EOD; | ||
1018 | + } | ||
1019 | + $setAttr[] = <<<EOD | ||
1020 | + protected function set{$attrField}Attr(\$value) | ||
1021 | + { | ||
1022 | + $return | ||
1023 | + } | ||
1024 | +EOD; | ||
1025 | + } | ||
1026 | + | ||
1027 | + protected function appendAttr(&$appendAttrList, $field) | ||
1028 | + { | ||
1029 | + $appendAttrList[] = <<<EOD | ||
1030 | + '{$field}_text' | ||
1031 | +EOD; | ||
1032 | + } | ||
1033 | + | ||
1034 | + /** | ||
1035 | + * 移除相对的空目录 | ||
1036 | + * @param $parseFile | ||
1037 | + * @param $parseArr | ||
1038 | + * @return bool | ||
1039 | + */ | ||
1040 | + protected function removeEmptyBaseDir($parseFile, $parseArr) | ||
1041 | + { | ||
1042 | + if (count($parseArr) > 1) { | ||
1043 | + $parentDir = dirname($parseFile); | ||
1044 | + for ($i = 0; $i < count($parseArr); $i++) { | ||
1045 | + try { | ||
1046 | + $iterator = new \FilesystemIterator($parentDir); | ||
1047 | + $isDirEmpty = !$iterator->valid(); | ||
1048 | + if ($isDirEmpty) { | ||
1049 | + rmdir($parentDir); | ||
1050 | + $parentDir = dirname($parentDir); | ||
1051 | + } else { | ||
1052 | + return true; | ||
1053 | + } | ||
1054 | + } catch (\UnexpectedValueException $e) { | ||
1055 | + return false; | ||
1056 | + } | ||
1057 | + } | ||
1058 | + } | ||
1059 | + return true; | ||
1060 | + } | ||
1061 | + | ||
1062 | + /** | ||
1063 | + * 获取控制器相关信息 | ||
1064 | + * @param $module | ||
1065 | + * @param $controller | ||
1066 | + * @param $table | ||
1067 | + * @return array | ||
1068 | + */ | ||
1069 | + protected function getControllerData($module, $controller, $table) | ||
1070 | + { | ||
1071 | + return $this->getParseNameData($module, $controller, $table, 'controller'); | ||
1072 | + } | ||
1073 | + | ||
1074 | + /** | ||
1075 | + * 获取模型相关信息 | ||
1076 | + * @param $module | ||
1077 | + * @param $model | ||
1078 | + * @param $table | ||
1079 | + * @return array | ||
1080 | + */ | ||
1081 | + protected function getModelData($module, $model, $table) | ||
1082 | + { | ||
1083 | + return $this->getParseNameData($module, $model, $table, 'model'); | ||
1084 | + } | ||
1085 | + | ||
1086 | + /** | ||
1087 | + * 获取验证器相关信息 | ||
1088 | + * @param $module | ||
1089 | + * @param $validate | ||
1090 | + * @param $table | ||
1091 | + * @return array | ||
1092 | + */ | ||
1093 | + protected function getValidateData($module, $validate, $table) | ||
1094 | + { | ||
1095 | + return $this->getParseNameData($module, $validate, $table, 'validate'); | ||
1096 | + } | ||
1097 | + | ||
1098 | + /** | ||
1099 | + * 获取已解析相关信息 | ||
1100 | + * @param string $module 模块名称 | ||
1101 | + * @param string $name 自定义名称 | ||
1102 | + * @param string $table 数据表名 | ||
1103 | + * @param string $type 解析类型,本例中为controller、model、validate | ||
1104 | + * @return array | ||
1105 | + */ | ||
1106 | + protected function getParseNameData($module, $name, $table, $type) | ||
1107 | + { | ||
1108 | + $arr = []; | ||
1109 | + if (!$name) { | ||
1110 | + $parseName = Loader::parseName($table, 1); | ||
1111 | + $parseArr = [$table]; | ||
1112 | + } else { | ||
1113 | + $name = str_replace(['.', '/', '\\'], '/', $name); | ||
1114 | + $arr = explode('/', $name); | ||
1115 | + $parseName = ucfirst(array_pop($arr)); | ||
1116 | + $parseArr = $arr; | ||
1117 | + array_push($parseArr, $parseName); | ||
1118 | + } | ||
1119 | + //类名不能为内部关键字 | ||
1120 | + if (in_array(strtolower($parseName), $this->internalKeywords)) { | ||
1121 | + throw new Exception('Unable to use internal variable:' . $parseName); | ||
1122 | + } | ||
1123 | + $appNamespace = Config::get('app_namespace'); | ||
1124 | + $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : ""); | ||
1125 | + $moduleDir = APP_PATH . $module . DS; | ||
1126 | + $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php'; | ||
1127 | + return [$parseNamespace, $parseName, $parseFile, $parseArr]; | ||
1128 | + } | ||
1129 | + | ||
1130 | + /** | ||
1131 | + * 写入到文件 | ||
1132 | + * @param string $name | ||
1133 | + * @param array $data | ||
1134 | + * @param string $pathname | ||
1135 | + * @return mixed | ||
1136 | + */ | ||
1137 | + protected function writeToFile($name, $data, $pathname) | ||
1138 | + { | ||
1139 | + foreach ($data as $index => &$datum) { | ||
1140 | + $datum = is_array($datum) ? '' : $datum; | ||
1141 | + } | ||
1142 | + unset($datum); | ||
1143 | + $content = $this->getReplacedStub($name, $data); | ||
1144 | + | ||
1145 | + if (!is_dir(dirname($pathname))) { | ||
1146 | + mkdir(dirname($pathname), 0755, true); | ||
1147 | + } | ||
1148 | + return file_put_contents($pathname, $content); | ||
1149 | + } | ||
1150 | + | ||
1151 | + /** | ||
1152 | + * 获取替换后的数据 | ||
1153 | + * @param string $name | ||
1154 | + * @param array $data | ||
1155 | + * @return string | ||
1156 | + */ | ||
1157 | + protected function getReplacedStub($name, $data) | ||
1158 | + { | ||
1159 | + foreach ($data as $index => &$datum) { | ||
1160 | + $datum = is_array($datum) ? '' : $datum; | ||
1161 | + } | ||
1162 | + unset($datum); | ||
1163 | + $search = $replace = []; | ||
1164 | + foreach ($data as $k => $v) { | ||
1165 | + $search[] = "{%{$k}%}"; | ||
1166 | + $replace[] = $v; | ||
1167 | + } | ||
1168 | + $stubname = $this->getStub($name); | ||
1169 | + if (isset($this->stubList[$stubname])) { | ||
1170 | + $stub = $this->stubList[$stubname]; | ||
1171 | + } else { | ||
1172 | + $this->stubList[$stubname] = $stub = file_get_contents($stubname); | ||
1173 | + } | ||
1174 | + $content = str_replace($search, $replace, $stub); | ||
1175 | + return $content; | ||
1176 | + } | ||
1177 | + | ||
1178 | + /** | ||
1179 | + * 获取基础模板 | ||
1180 | + * @param string $name | ||
1181 | + * @return string | ||
1182 | + */ | ||
1183 | + protected function getStub($name) | ||
1184 | + { | ||
1185 | + return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub'; | ||
1186 | + } | ||
1187 | + | ||
1188 | + protected function getLangItem($field, $content) | ||
1189 | + { | ||
1190 | + if ($content || !Lang::has($field)) { | ||
1191 | + $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen; | ||
1192 | + $content = str_replace(',', ',', $content); | ||
1193 | + if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) { | ||
1194 | + list($fieldLang, $item) = explode(':', $content); | ||
1195 | + $itemArr = [$field => $fieldLang]; | ||
1196 | + foreach (explode(',', $item) as $k => $v) { | ||
1197 | + $valArr = explode('=', $v); | ||
1198 | + if (count($valArr) == 2) { | ||
1199 | + list($key, $value) = $valArr; | ||
1200 | + $itemArr[$field . ' ' . $key] = $value; | ||
1201 | + $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen; | ||
1202 | + } | ||
1203 | + } | ||
1204 | + } else { | ||
1205 | + $itemArr = [$field => $content]; | ||
1206 | + } | ||
1207 | + $resultArr = []; | ||
1208 | + foreach ($itemArr as $k => $v) { | ||
1209 | + $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'"; | ||
1210 | + } | ||
1211 | + return implode(",\n", $resultArr); | ||
1212 | + } else { | ||
1213 | + return ''; | ||
1214 | + } | ||
1215 | + } | ||
1216 | + | ||
1217 | + /** | ||
1218 | + * 读取数据和语言数组列表 | ||
1219 | + * @param array $arr | ||
1220 | + * @param boolean $withTpl | ||
1221 | + * @return array | ||
1222 | + */ | ||
1223 | + protected function getLangArray($arr, $withTpl = true) | ||
1224 | + { | ||
1225 | + $langArr = []; | ||
1226 | + foreach ($arr as $k => $v) { | ||
1227 | + $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v; | ||
1228 | + } | ||
1229 | + return $langArr; | ||
1230 | + } | ||
1231 | + | ||
1232 | + /** | ||
1233 | + * 将数据转换成带字符串 | ||
1234 | + * @param array $arr | ||
1235 | + * @return string | ||
1236 | + */ | ||
1237 | + protected function getArrayString($arr) | ||
1238 | + { | ||
1239 | + if (!is_array($arr)) { | ||
1240 | + return $arr; | ||
1241 | + } | ||
1242 | + $stringArr = []; | ||
1243 | + foreach ($arr as $k => $v) { | ||
1244 | + $is_var = in_array(substr($v, 0, 1), ['$', '_']); | ||
1245 | + if (!$is_var) { | ||
1246 | + $v = str_replace("'", "\'", $v); | ||
1247 | + $k = str_replace("'", "\'", $k); | ||
1248 | + } | ||
1249 | + $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'"); | ||
1250 | + } | ||
1251 | + return implode(", ", $stringArr); | ||
1252 | + } | ||
1253 | + | ||
1254 | + protected function getItemArray($item, $field, $comment) | ||
1255 | + { | ||
1256 | + $itemArr = []; | ||
1257 | + $comment = str_replace(',', ',', $comment); | ||
1258 | + if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) { | ||
1259 | + list($fieldLang, $item) = explode(':', $comment); | ||
1260 | + $itemArr = []; | ||
1261 | + foreach (explode(',', $item) as $k => $v) { | ||
1262 | + $valArr = explode('=', $v); | ||
1263 | + if (count($valArr) == 2) { | ||
1264 | + list($key, $value) = $valArr; | ||
1265 | + $itemArr[$key] = $field . ' ' . $key; | ||
1266 | + } | ||
1267 | + } | ||
1268 | + } else { | ||
1269 | + foreach ($item as $k => $v) { | ||
1270 | + $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v; | ||
1271 | + } | ||
1272 | + } | ||
1273 | + return $itemArr; | ||
1274 | + } | ||
1275 | + | ||
1276 | + protected function getFieldType(& $v) | ||
1277 | + { | ||
1278 | + $inputType = 'text'; | ||
1279 | + switch ($v['DATA_TYPE']) { | ||
1280 | + case 'bigint': | ||
1281 | + case 'int': | ||
1282 | + case 'mediumint': | ||
1283 | + case 'smallint': | ||
1284 | + case 'tinyint': | ||
1285 | + $inputType = 'number'; | ||
1286 | + break; | ||
1287 | + case 'enum': | ||
1288 | + case 'set': | ||
1289 | + $inputType = 'select'; | ||
1290 | + break; | ||
1291 | + case 'decimal': | ||
1292 | + case 'double': | ||
1293 | + case 'float': | ||
1294 | + $inputType = 'number'; | ||
1295 | + break; | ||
1296 | + case 'longtext': | ||
1297 | + case 'text': | ||
1298 | + case 'mediumtext': | ||
1299 | + case 'smalltext': | ||
1300 | + case 'tinytext': | ||
1301 | + $inputType = 'textarea'; | ||
1302 | + break; | ||
1303 | + case 'year': | ||
1304 | + case 'date': | ||
1305 | + case 'time': | ||
1306 | + case 'datetime': | ||
1307 | + case 'timestamp': | ||
1308 | + $inputType = 'datetime'; | ||
1309 | + break; | ||
1310 | + default: | ||
1311 | + break; | ||
1312 | + } | ||
1313 | + $fieldsName = $v['COLUMN_NAME']; | ||
1314 | + // 指定后缀说明也是个时间字段 | ||
1315 | + if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) { | ||
1316 | + $inputType = 'datetime'; | ||
1317 | + } | ||
1318 | + // 指定后缀结尾且类型为enum,说明是个单选框 | ||
1319 | + if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') { | ||
1320 | + $inputType = "radio"; | ||
1321 | + } | ||
1322 | + // 指定后缀结尾且类型为set,说明是个复选框 | ||
1323 | + if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') { | ||
1324 | + $inputType = "checkbox"; | ||
1325 | + } | ||
1326 | + // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框 | ||
1327 | + if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) { | ||
1328 | + $inputType = "switch"; | ||
1329 | + } | ||
1330 | + // 指定后缀结尾城市选择框 | ||
1331 | + if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) { | ||
1332 | + $inputType = "citypicker"; | ||
1333 | + } | ||
1334 | + // 指定后缀结尾JSON配置 | ||
1335 | + if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) { | ||
1336 | + $inputType = "fieldlist"; | ||
1337 | + } | ||
1338 | + return $inputType; | ||
1339 | + } | ||
1340 | + | ||
1341 | + /** | ||
1342 | + * 判断是否符合指定后缀 | ||
1343 | + * @param string $field 字段名称 | ||
1344 | + * @param mixed $suffixArr 后缀 | ||
1345 | + * @return boolean | ||
1346 | + */ | ||
1347 | + protected function isMatchSuffix($field, $suffixArr) | ||
1348 | + { | ||
1349 | + $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr); | ||
1350 | + foreach ($suffixArr as $k => $v) { | ||
1351 | + if (preg_match("/{$v}$/i", $field)) { | ||
1352 | + return true; | ||
1353 | + } | ||
1354 | + } | ||
1355 | + return false; | ||
1356 | + } | ||
1357 | + | ||
1358 | + /** | ||
1359 | + * 获取表单分组数据 | ||
1360 | + * @param string $field | ||
1361 | + * @param string $content | ||
1362 | + * @return string | ||
1363 | + */ | ||
1364 | + protected function getFormGroup($field, $content) | ||
1365 | + { | ||
1366 | + $langField = mb_ucfirst($field); | ||
1367 | + return <<<EOD | ||
1368 | + <div class="form-group"> | ||
1369 | + <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label> | ||
1370 | + <div class="col-xs-12 col-sm-8"> | ||
1371 | + {$content} | ||
1372 | + </div> | ||
1373 | + </div> | ||
1374 | +EOD; | ||
1375 | + } | ||
1376 | + | ||
1377 | + /** | ||
1378 | + * 获取图片模板数据 | ||
1379 | + * @param string $field | ||
1380 | + * @param string $content | ||
1381 | + * @return string | ||
1382 | + */ | ||
1383 | + protected function getImageUpload($field, $content) | ||
1384 | + { | ||
1385 | + $uploadfilter = $selectfilter = ''; | ||
1386 | + if ($this->isMatchSuffix($field, $this->imageField)) { | ||
1387 | + $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"'; | ||
1388 | + $selectfilter = ' data-mimetype="image/*"'; | ||
1389 | + } | ||
1390 | + $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"'; | ||
1391 | + $preview = ' data-preview-id="p-' . $field . '"'; | ||
1392 | + $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : ''; | ||
1393 | + return <<<EOD | ||
1394 | +<div class="input-group"> | ||
1395 | + {$content} | ||
1396 | + <div class="input-group-addon no-border no-padding"> | ||
1397 | + <span><button type="button" id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span> | ||
1398 | + <span><button type="button" id="fachoose-{$field}" class="btn btn-primary fachoose" data-input-id="c-{$field}"{$selectfilter}{$multiple}><i class="fa fa-list"></i> {:__('Choose')}</button></span> | ||
1399 | + </div> | ||
1400 | + <span class="msg-box n-right" for="c-{$field}"></span> | ||
1401 | + </div> | ||
1402 | + {$previewcontainer} | ||
1403 | +EOD; | ||
1404 | + } | ||
1405 | + | ||
1406 | + /** | ||
1407 | + * 获取JS列数据 | ||
1408 | + * @param string $field | ||
1409 | + * @param string $datatype | ||
1410 | + * @param string $extend | ||
1411 | + * @param array $itemArr | ||
1412 | + * @return string | ||
1413 | + */ | ||
1414 | + protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = []) | ||
1415 | + { | ||
1416 | + $lang = mb_ucfirst($field); | ||
1417 | + $formatter = ''; | ||
1418 | + foreach ($this->fieldFormatterSuffix as $k => $v) { | ||
1419 | + if (preg_match("/{$k}$/i", $field)) { | ||
1420 | + if (is_array($v)) { | ||
1421 | + if (in_array($datatype, $v['type'])) { | ||
1422 | + $formatter = $v['name']; | ||
1423 | + break; | ||
1424 | + } | ||
1425 | + } else { | ||
1426 | + $formatter = $v; | ||
1427 | + break; | ||
1428 | + } | ||
1429 | + } | ||
1430 | + } | ||
1431 | + $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')"; | ||
1432 | + | ||
1433 | + if ($datatype == 'set') { | ||
1434 | + $formatter = 'label'; | ||
1435 | + } | ||
1436 | + foreach ($itemArr as $k => &$v) { | ||
1437 | + if (substr($v, 0, 3) !== '__(') { | ||
1438 | + $v = "__('" . mb_ucfirst($v) . "')"; | ||
1439 | + } | ||
1440 | + } | ||
1441 | + unset($v); | ||
1442 | + $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE); | ||
1443 | + $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList); | ||
1444 | + if ($itemArr) { | ||
1445 | + $html .= ", searchList: " . $searchList; | ||
1446 | + } | ||
1447 | + if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') { | ||
1448 | + $html .= ", operate:'RANGE', addclass:'datetimerange'"; | ||
1449 | + } elseif (in_array($datatype, ['float', 'double', 'decimal'])) { | ||
1450 | + $html .= ", operate:'BETWEEN'"; | ||
1451 | + } | ||
1452 | + if (in_array($datatype, ['set'])) { | ||
1453 | + $html .= ", operate:'FIND_IN_SET'"; | ||
1454 | + } | ||
1455 | + if (in_array($formatter, ['image', 'images'])) { | ||
1456 | + $html .= ", events: Table.api.events.image"; | ||
1457 | + } | ||
1458 | + if ($itemArr && !$formatter) { | ||
1459 | + $formatter = 'normal'; | ||
1460 | + } | ||
1461 | + if ($formatter) { | ||
1462 | + $html .= ", formatter: Table.api.formatter." . $formatter . "}"; | ||
1463 | + } else { | ||
1464 | + $html .= "}"; | ||
1465 | + } | ||
1466 | + return $html; | ||
1467 | + } | ||
1468 | + | ||
1469 | + protected function getCamelizeName($uncamelized_words, $separator = '_') | ||
1470 | + { | ||
1471 | + $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words)); | ||
1472 | + return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator); | ||
1473 | + } | ||
1474 | + | ||
1475 | + protected function getFieldListName($field) | ||
1476 | + { | ||
1477 | + return $this->getCamelizeName($field) . 'List'; | ||
1478 | + } | ||
1479 | +} |
1 | +<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action=""> | ||
2 | + | ||
3 | +{%addList%} | ||
4 | + <div class="form-group layer-footer"> | ||
5 | + <label class="control-label col-xs-12 col-sm-2"></label> | ||
6 | + <div class="col-xs-12 col-sm-8"> | ||
7 | + <button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button> | ||
8 | + <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button> | ||
9 | + </div> | ||
10 | + </div> | ||
11 | +</form> |
1 | +<?php | ||
2 | + | ||
3 | +namespace {%controllerNamespace%}; | ||
4 | + | ||
5 | +use app\common\controller\Backend; | ||
6 | + | ||
7 | +/** | ||
8 | + * {%tableComment%} | ||
9 | + * | ||
10 | + * @icon {%iconName%} | ||
11 | + */ | ||
12 | +class {%controllerName%} extends Backend | ||
13 | +{ | ||
14 | + | ||
15 | + /** | ||
16 | + * {%modelName%}模型对象 | ||
17 | + * @var \{%modelNamespace%}\{%modelName%} | ||
18 | + */ | ||
19 | + protected $model = null; | ||
20 | + | ||
21 | + public function _initialize() | ||
22 | + { | ||
23 | + parent::_initialize(); | ||
24 | + $this->model = new \{%modelNamespace%}\{%modelName%}; | ||
25 | +{%controllerAssignList%} | ||
26 | + } | ||
27 | + | ||
28 | + /** | ||
29 | + * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法 | ||
30 | + * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑 | ||
31 | + * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改 | ||
32 | + */ | ||
33 | + | ||
34 | +{%controllerIndex%} | ||
35 | +} |
1 | + | ||
2 | + /** | ||
3 | + * 查看 | ||
4 | + */ | ||
5 | + public function index() | ||
6 | + { | ||
7 | + //当前是否为关联查询 | ||
8 | + $this->relationSearch = {%relationSearch%}; | ||
9 | + //设置过滤方法 | ||
10 | + $this->request->filter(['strip_tags', 'trim']); | ||
11 | + if ($this->request->isAjax()) | ||
12 | + { | ||
13 | + //如果发送的来源是Selectpage,则转发到Selectpage | ||
14 | + if ($this->request->request('keyField')) | ||
15 | + { | ||
16 | + return $this->selectpage(); | ||
17 | + } | ||
18 | + list($where, $sort, $order, $offset, $limit) = $this->buildparams(); | ||
19 | + $total = $this->model | ||
20 | + {%relationWithList%} | ||
21 | + ->where($where) | ||
22 | + ->order($sort, $order) | ||
23 | + ->count(); | ||
24 | + | ||
25 | + $list = $this->model | ||
26 | + {%relationWithList%} | ||
27 | + ->where($where) | ||
28 | + ->order($sort, $order) | ||
29 | + ->limit($offset, $limit) | ||
30 | + ->select(); | ||
31 | + | ||
32 | + foreach ($list as $row) { | ||
33 | + {%visibleFieldList%} | ||
34 | + {%relationVisibleFieldList%} | ||
35 | + } | ||
36 | + $list = collection($list)->toArray(); | ||
37 | + $result = array("total" => $total, "rows" => $list); | ||
38 | + | ||
39 | + return json($result); | ||
40 | + } | ||
41 | + return $this->view->fetch(); | ||
42 | + } |
1 | +<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action=""> | ||
2 | + | ||
3 | +{%editList%} | ||
4 | + <div class="form-group layer-footer"> | ||
5 | + <label class="control-label col-xs-12 col-sm-2"></label> | ||
6 | + <div class="col-xs-12 col-sm-8"> | ||
7 | + <button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button> | ||
8 | + <button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button> | ||
9 | + </div> | ||
10 | + </div> | ||
11 | +</form> |
1 | + | ||
2 | + <dl class="fieldlist" data-name="{%fieldName%}"> | ||
3 | + <dd> | ||
4 | + <ins>{:__('{%itemKey%}')}</ins> | ||
5 | + <ins>{:__('{%itemValue%}')}</ins> | ||
6 | + </dd> | ||
7 | + <dd><a href="javascript:;" class="btn btn-sm btn-success btn-append"><i class="fa fa-plus"></i> {:__('Append')}</a></dd> | ||
8 | + <textarea name="{%fieldName%}" class="form-control hide" cols="30" rows="5">{%fieldValue%}</textarea> | ||
9 | + </dl> | ||
10 | + |
1 | + | ||
2 | + <div class="panel-heading"> | ||
3 | + {:build_heading(null,FALSE)} | ||
4 | + <ul class="nav nav-tabs" data-field="{%field%}"> | ||
5 | + <li class="active"><a href="#t-all" data-value="" data-toggle="tab">{:__('All')}</a></li> | ||
6 | + {foreach name="{%fieldName%}List" item="vo"} | ||
7 | + <li><a href="#t-{$key}" data-value="{$key}" data-toggle="tab">{$vo}</a></li> | ||
8 | + {/foreach} | ||
9 | + </ul> | ||
10 | + </div> |
1 | +<a class="btn btn-success btn-recyclebin btn-dialog {:$auth->check('{%controllerUrl%}/recyclebin')?'':'hide'}" href="{%controllerUrl%}/recyclebin" title="{:__('Recycle bin')}"><i class="fa fa-recycle"></i> {:__('Recycle bin')}</a> |
1 | + | ||
2 | + <input {%attrStr%} name="{%fieldName%}" type="hidden" value="{%fieldValue%}"> | ||
3 | + <a href="javascript:;" data-toggle="switcher" class="btn-switcher" data-input-id="c-{%field%}" data-yes="{%fieldYes%}" data-no="{%fieldNo%}" > | ||
4 | + <i class="fa fa-toggle-on text-success {%fieldSwitchClass%} fa-2x"></i> | ||
5 | + </a> |
1 | +<div class="panel panel-default panel-intro"> | ||
2 | + {%headingHtml%} | ||
3 | + | ||
4 | + <div class="panel-body"> | ||
5 | + <div id="myTabContent" class="tab-content"> | ||
6 | + <div class="tab-pane fade active in" id="one"> | ||
7 | + <div class="widget-body no-padding"> | ||
8 | + <div id="toolbar" class="toolbar"> | ||
9 | + <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a> | ||
10 | + <a href="javascript:;" class="btn btn-success btn-add {:$auth->check('{%controllerUrl%}/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a> | ||
11 | + <a href="javascript:;" class="btn btn-success btn-edit btn-disabled disabled {:$auth->check('{%controllerUrl%}/edit')?'':'hide'}" title="{:__('Edit')}" ><i class="fa fa-pencil"></i> {:__('Edit')}</a> | ||
12 | + <a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('{%controllerUrl%}/del')?'':'hide'}" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a> | ||
13 | + <a href="javascript:;" class="btn btn-danger btn-import {:$auth->check('{%controllerUrl%}/import')?'':'hide'}" title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> {:__('Import')}</a> | ||
14 | + | ||
15 | + <div class="dropdown btn-group {:$auth->check('{%controllerUrl%}/multi')?'':'hide'}"> | ||
16 | + <a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> {:__('More')}</a> | ||
17 | + <ul class="dropdown-menu text-left" role="menu"> | ||
18 | + <li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=normal"><i class="fa fa-eye"></i> {:__('Set to normal')}</a></li> | ||
19 | + <li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li> | ||
20 | + </ul> | ||
21 | + </div> | ||
22 | + | ||
23 | + {%recyclebinHtml%} | ||
24 | + </div> | ||
25 | + <table id="table" class="table table-striped table-bordered table-hover table-nowrap" | ||
26 | + data-operate-edit="{:$auth->check('{%controllerUrl%}/edit')}" | ||
27 | + data-operate-del="{:$auth->check('{%controllerUrl%}/del')}" | ||
28 | + width="100%"> | ||
29 | + </table> | ||
30 | + </div> | ||
31 | + </div> | ||
32 | + | ||
33 | + </div> | ||
34 | + </div> | ||
35 | +</div> |
1 | +define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) { | ||
2 | + | ||
3 | + var Controller = { | ||
4 | + index: function () { | ||
5 | + // 初始化表格参数配置 | ||
6 | + Table.api.init({ | ||
7 | + extend: { | ||
8 | + index_url: '{%controllerUrl%}/index' + location.search, | ||
9 | + add_url: '{%controllerUrl%}/add', | ||
10 | + edit_url: '{%controllerUrl%}/edit', | ||
11 | + del_url: '{%controllerUrl%}/del', | ||
12 | + multi_url: '{%controllerUrl%}/multi', | ||
13 | + table: '{%table%}', | ||
14 | + } | ||
15 | + }); | ||
16 | + | ||
17 | + var table = $("#table"); | ||
18 | + | ||
19 | + // 初始化表格 | ||
20 | + table.bootstrapTable({ | ||
21 | + url: $.fn.bootstrapTable.defaults.extend.index_url, | ||
22 | + pk: '{%pk%}', | ||
23 | + sortName: '{%order%}', | ||
24 | + columns: [ | ||
25 | + [ | ||
26 | + {%javascriptList%} | ||
27 | + ] | ||
28 | + ] | ||
29 | + }); | ||
30 | + | ||
31 | + // 为表格绑定事件 | ||
32 | + Table.api.bindevent(table); | ||
33 | + },{%recyclebinJs%} | ||
34 | + add: function () { | ||
35 | + Controller.api.bindevent(); | ||
36 | + }, | ||
37 | + edit: function () { | ||
38 | + Controller.api.bindevent(); | ||
39 | + }, | ||
40 | + api: { | ||
41 | + bindevent: function () { | ||
42 | + Form.api.bindevent($("form[role=form]")); | ||
43 | + } | ||
44 | + } | ||
45 | + }; | ||
46 | + return Controller; | ||
47 | +}); |
1 | + | ||
2 | + public function {%methodName%}($value, $data) | ||
3 | + { | ||
4 | + $value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : ''); | ||
5 | + $valueArr = explode(',', $value); | ||
6 | + $list = $this->{%listMethodName%}(); | ||
7 | + return implode(',', array_intersect_key($list, array_flip($valueArr))); | ||
8 | + } |
1 | + |
1 | + | ||
2 | + public function {%methodName%}($value, $data) | ||
3 | + { | ||
4 | + $value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : ''); | ||
5 | + $valueArr = explode(',', $value); | ||
6 | + $list = $this->{%listMethodName%}(); | ||
7 | + return implode(',', array_intersect_key($list, array_flip($valueArr))); | ||
8 | + } |
1 | + | ||
2 | + recyclebin: function () { | ||
3 | + // 初始化表格参数配置 | ||
4 | + Table.api.init({ | ||
5 | + extend: { | ||
6 | + 'dragsort_url': '' | ||
7 | + } | ||
8 | + }); | ||
9 | + | ||
10 | + var table = $("#table"); | ||
11 | + | ||
12 | + // 初始化表格 | ||
13 | + table.bootstrapTable({ | ||
14 | + url: '{%controllerUrl%}/recyclebin' + location.search, | ||
15 | + pk: 'id', | ||
16 | + sortName: 'id', | ||
17 | + columns: [ | ||
18 | + [ | ||
19 | + {checkbox: true}, | ||
20 | + {field: 'id', title: __('Id')},{%recyclebinTitleJs%} | ||
21 | + { | ||
22 | + field: 'deletetime', | ||
23 | + title: __('Deletetime'), | ||
24 | + operate: 'RANGE', | ||
25 | + addclass: 'datetimerange', | ||
26 | + formatter: Table.api.formatter.datetime | ||
27 | + }, | ||
28 | + { | ||
29 | + field: 'operate', | ||
30 | + width: '130px', | ||
31 | + title: __('Operate'), | ||
32 | + table: table, | ||
33 | + events: Table.api.events.operate, | ||
34 | + buttons: [ | ||
35 | + { | ||
36 | + name: 'Restore', | ||
37 | + text: __('Restore'), | ||
38 | + classname: 'btn btn-xs btn-info btn-ajax btn-restoreit', | ||
39 | + icon: 'fa fa-rotate-left', | ||
40 | + url: '{%controllerUrl%}/restore', | ||
41 | + refresh: true | ||
42 | + }, | ||
43 | + { | ||
44 | + name: 'Destroy', | ||
45 | + text: __('Destroy'), | ||
46 | + classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit', | ||
47 | + icon: 'fa fa-times', | ||
48 | + url: '{%controllerUrl%}/destroy', | ||
49 | + refresh: true | ||
50 | + } | ||
51 | + ], | ||
52 | + formatter: Table.api.formatter.operate | ||
53 | + } | ||
54 | + ] | ||
55 | + ] | ||
56 | + }); | ||
57 | + | ||
58 | + // 为表格绑定事件 | ||
59 | + Table.api.bindevent(table); | ||
60 | + }, |
1 | +<?php | ||
2 | + | ||
3 | +namespace {%modelNamespace%}; | ||
4 | + | ||
5 | +use think\Model; | ||
6 | +{%sofeDeleteClassPath%} | ||
7 | + | ||
8 | +class {%modelName%} extends Model | ||
9 | +{ | ||
10 | + | ||
11 | + {%softDelete%} | ||
12 | + | ||
13 | + {%modelConnection%} | ||
14 | + | ||
15 | + // 表名 | ||
16 | + protected ${%modelTableType%} = '{%modelTableTypeName%}'; | ||
17 | + | ||
18 | + // 自动写入时间戳字段 | ||
19 | + protected $autoWriteTimestamp = {%modelAutoWriteTimestamp%}; | ||
20 | + | ||
21 | + // 定义时间戳字段名 | ||
22 | + protected $createTime = {%createTime%}; | ||
23 | + protected $updateTime = {%updateTime%}; | ||
24 | + protected $deleteTime = {%deleteTime%}; | ||
25 | + | ||
26 | + // 追加属性 | ||
27 | + protected $append = [ | ||
28 | +{%appendAttrList%} | ||
29 | + ]; | ||
30 | + | ||
31 | +{%modelInit%} | ||
32 | + | ||
33 | +{%getEnumList%} | ||
34 | + | ||
35 | +{%getAttrList%} | ||
36 | + | ||
37 | +{%setAttrList%} | ||
38 | + | ||
39 | +{%relationMethodList%} | ||
40 | +} |
1 | +<div class="panel panel-default panel-intro"> | ||
2 | + {:build_heading()} | ||
3 | + | ||
4 | + <div class="panel-body"> | ||
5 | + <div id="myTabContent" class="tab-content"> | ||
6 | + <div class="tab-pane fade active in" id="one"> | ||
7 | + <div class="widget-body no-padding"> | ||
8 | + <div id="toolbar" class="toolbar"> | ||
9 | + {:build_toolbar('refresh')} | ||
10 | + <a class="btn btn-info btn-multi btn-disabled disabled {:$auth->check('{%controllerUrl%}/restore')?'':'hide'}" href="javascript:;" data-url="{%controllerUrl%}/restore" data-action="restore"><i class="fa fa-rotate-left"></i> {:__('Restore')}</a> | ||
11 | + <a class="btn btn-danger btn-multi btn-disabled disabled {:$auth->check('{%controllerUrl%}/destroy')?'':'hide'}" href="javascript:;" data-url="{%controllerUrl%}/destroy" data-action="destroy"><i class="fa fa-times"></i> {:__('Destroy')}</a> | ||
12 | + <a class="btn btn-success btn-restoreall {:$auth->check('{%controllerUrl%}/restore')?'':'hide'}" href="javascript:;" data-url="{%controllerUrl%}/restore" title="{:__('Restore all')}"><i class="fa fa-rotate-left"></i> {:__('Restore all')}</a> | ||
13 | + <a class="btn btn-danger btn-destroyall {:$auth->check('{%controllerUrl%}/destroy')?'':'hide'}" href="javascript:;" data-url="{%controllerUrl%}/destroy" title="{:__('Destroy all')}"><i class="fa fa-times"></i> {:__('Destroy all')}</a> | ||
14 | + </div> | ||
15 | + <table id="table" class="table table-striped table-bordered table-hover" | ||
16 | + data-operate-restore="{:$auth->check('{%controllerUrl%}/restore')}" | ||
17 | + data-operate-destroy="{:$auth->check('{%controllerUrl%}/destroy')}" | ||
18 | + width="100%"> | ||
19 | + </table> | ||
20 | + </div> | ||
21 | + </div> | ||
22 | + | ||
23 | + </div> | ||
24 | + </div> | ||
25 | +</div> |
1 | +<?php | ||
2 | + | ||
3 | +namespace {%validateNamespace%}; | ||
4 | + | ||
5 | +use think\Validate; | ||
6 | + | ||
7 | +class {%validateName%} extends Validate | ||
8 | +{ | ||
9 | + /** | ||
10 | + * 验证规则 | ||
11 | + */ | ||
12 | + protected $rule = [ | ||
13 | + ]; | ||
14 | + /** | ||
15 | + * 提示消息 | ||
16 | + */ | ||
17 | + protected $message = [ | ||
18 | + ]; | ||
19 | + /** | ||
20 | + * 验证场景 | ||
21 | + */ | ||
22 | + protected $scene = [ | ||
23 | + 'add' => [], | ||
24 | + 'edit' => [], | ||
25 | + ]; | ||
26 | + | ||
27 | +} |
application/admin/command/Install.php
0 → 100644
1 | +<?php | ||
2 | + | ||
3 | +namespace app\admin\command; | ||
4 | + | ||
5 | +use PDO; | ||
6 | +use think\Config; | ||
7 | +use think\console\Command; | ||
8 | +use think\console\Input; | ||
9 | +use think\console\input\Option; | ||
10 | +use think\console\Output; | ||
11 | +use think\Db; | ||
12 | +use think\Exception; | ||
13 | + | ||
14 | +class Install extends Command | ||
15 | +{ | ||
16 | + protected $model = null; | ||
17 | + | ||
18 | + protected function configure() | ||
19 | + { | ||
20 | + $config = Config::get('database'); | ||
21 | + $this | ||
22 | + ->setName('install') | ||
23 | + ->addOption('hostname', 'a', Option::VALUE_OPTIONAL, 'mysql hostname', $config['hostname']) | ||
24 | + ->addOption('hostport', 'o', Option::VALUE_OPTIONAL, 'mysql hostport', $config['hostport']) | ||
25 | + ->addOption('database', 'd', Option::VALUE_OPTIONAL, 'mysql database', $config['database']) | ||
26 | + ->addOption('prefix', 'r', Option::VALUE_OPTIONAL, 'table prefix', $config['prefix']) | ||
27 | + ->addOption('username', 'u', Option::VALUE_OPTIONAL, 'mysql username', $config['username']) | ||
28 | + ->addOption('password', 'p', Option::VALUE_OPTIONAL, 'mysql password', $config['password']) | ||
29 | + ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', false) | ||
30 | + ->setDescription('New installation of FastAdmin'); | ||
31 | + } | ||
32 | + | ||
33 | + protected function execute(Input $input, Output $output) | ||
34 | + { | ||
35 | + // 覆盖安装 | ||
36 | + $force = $input->getOption('force'); | ||
37 | + $hostname = $input->getOption('hostname'); | ||
38 | + $hostport = $input->getOption('hostport'); | ||
39 | + $database = $input->getOption('database'); | ||
40 | + $prefix = $input->getOption('prefix'); | ||
41 | + $username = $input->getOption('username'); | ||
42 | + $password = $input->getOption('password'); | ||
43 | + | ||
44 | + $installLockFile = __DIR__ . "/Install/install.lock"; | ||
45 | + if (is_file($installLockFile) && !$force) { | ||
46 | + throw new Exception("\nFastAdmin already installed!\nIf you need to reinstall again, use the parameter --force=true "); | ||
47 | + } | ||
48 | + | ||
49 | + $sql = file_get_contents(__DIR__ . '/Install/fastadmin.sql'); | ||
50 | + | ||
51 | + $sql = str_replace("`fa_", "`{$prefix}", $sql); | ||
52 | + | ||
53 | + // 先尝试能否自动创建数据库 | ||
54 | + $config = Config::get('database'); | ||
55 | + $pdo = new PDO("{$config['type']}:host={$hostname}" . ($hostport ? ";port={$hostport}" : ''), $username, $password); | ||
56 | + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | ||
57 | + $pdo->query("CREATE DATABASE IF NOT EXISTS `{$database}` CHARACTER SET utf8 COLLATE utf8_general_ci;"); | ||
58 | + | ||
59 | + // 连接install命令中指定的数据库 | ||
60 | + $instance = Db::connect([ | ||
61 | + 'type' => "{$config['type']}", | ||
62 | + 'hostname' => "{$hostname}", | ||
63 | + 'hostport' => "{$hostport}", | ||
64 | + 'database' => "{$database}", | ||
65 | + 'username' => "{$username}", | ||
66 | + 'password' => "{$password}", | ||
67 | + ]); | ||
68 | + | ||
69 | + // 查询一次SQL,判断连接是否正常 | ||
70 | + $instance->execute("SELECT 1"); | ||
71 | + | ||
72 | + // 调用原生PDO对象进行批量查询 | ||
73 | + $instance->getPdo()->exec($sql); | ||
74 | + | ||
75 | + file_put_contents($installLockFile, 1); | ||
76 | + | ||
77 | + //后台入口文件 | ||
78 | + $adminFile = ROOT_PATH . 'public' . DS . 'admin.php'; | ||
79 | + | ||
80 | + $dbConfigFile = APP_PATH . 'database.php'; | ||
81 | + $config = @file_get_contents($dbConfigFile); | ||
82 | + $callback = function ($matches) use ($hostname, $hostport, $username, $password, $database, $prefix) { | ||
83 | + $field = $matches[1]; | ||
84 | + $replace = $$field; | ||
85 | + if ($matches[1] == 'hostport' && $hostport == 3306) { | ||
86 | + $replace = ''; | ||
87 | + } | ||
88 | + return "'{$matches[1]}'{$matches[2]}=>{$matches[3]}Env::get('database.{$matches[1]}', '{$replace}'),"; | ||
89 | + }; | ||
90 | + $config = preg_replace_callback("/'(hostname|database|username|password|hostport|prefix)'(\s+)=>(\s+)Env::get\((.*)\)\,/", $callback, $config); | ||
91 | + // 写入数据库配置 | ||
92 | + file_put_contents($dbConfigFile, $config); | ||
93 | + | ||
94 | + // 修改后台入口 | ||
95 | + if (is_file($adminFile)) { | ||
96 | + $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | ||
97 | + $adminName = substr(str_shuffle(str_repeat($x, ceil(10 / strlen($x)))), 1, 10) . '.php'; | ||
98 | + rename($adminFile, ROOT_PATH . 'public' . DS . $adminName); | ||
99 | + $output->highlight("Admin url:http://www.yoursite.com/{$adminName}"); | ||
100 | + } | ||
101 | + $output->highlight("Admin username:admin"); | ||
102 | + $output->highlight("Admin password:123456"); | ||
103 | + | ||
104 | + \think\Cache::rm('__menu__'); | ||
105 | + | ||
106 | + $output->info("Install Successed!"); | ||
107 | + } | ||
108 | +} |
-
请 注册 或 登录 后发表评论