作者 王智

'源码'

正在显示 46 个修改的文件 包含 4626 行增加0 行删除

要显示太多修改。

为保证性能只显示 46 of 46+ 个文件。

  1 +{
  2 + "directory": "public/assets/libs",
  3 + "ignoredDependencies": [
  4 + "es6-promise",
  5 + "file-saver",
  6 + "html2canvas",
  7 + "jspdf",
  8 + "jspdf-autotable"
  9 + ]
  10 +}
  1 +[app]
  2 +debug = false
  3 +trace = false
  4 +
  5 +[database]
  6 +hostname = 127.0.0.1
  7 +database = fastadmin
  8 +username = root
  9 +password = root
  10 +hostport = 3306
  11 +prefix = fa_
  1 +database.php
  2 +/nbproject/
  3 +/runtime/*
  4 +/public/uploads/*
  5 +.idea
  6 +composer.lock
  7 +*.log
  8 +*.css.map
  9 +!.gitkeep
  10 +.env
  11 +.svn
  12 +.vscode
  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.
  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 +* 强大的插件扩展功能,在线安装卸载升级插件
  21 +* 通用的会员模块和API模块
  22 +* 共用同一账号体系的Web端会员中心权限验证和API接口会员权限验证
  23 +* 二级域名部署支持,同时域名支持绑定到应用插件
  24 +* 多语言支持,服务端及客户端支持
  25 +* 支持大文件分片上传、剪切板粘贴上传、拖拽上传,进度条显示,图片上传前压缩
  26 +* 支持表格固定列、固定表头、跨页选择、Excel导出、模板渲染等功能
  27 +* 强大的第三方应用模块支持([CMS](https://www.fastadmin.net/store/cms.html)[博客](https://www.fastadmin.net/store/blog.html)[知识付费问答](https://www.fastadmin.net/store/ask.html)[在线投票系统](https://www.fastadmin.net/store/vote.html)[B2C商城](https://www.fastadmin.net/store/shopro.html)[B2B2C商城](https://www.fastadmin.net/store/wanlshop.html))
  28 +* 支持CMS、博客、知识付费问答无缝整合[Xunsearch全文搜索](https://www.fastadmin.net/store/xunsearch.html)
  29 +* 第三方小程序支持([CMS小程序](https://www.fastadmin.net/store/cms.html)[预订小程序](https://www.fastadmin.net/store/ball.html)[问答小程序](https://www.fastadmin.net/store/ask.html)[点餐小程序](https://www.fastadmin.net/store/unidrink.html)[B2C小程序](https://www.fastadmin.net/store/shopro.html)[B2B2C小程序](https://www.fastadmin.net/store/wanlshop.html)[博客小程序](https://www.fastadmin.net/store/blog.html))
  30 +* 整合第三方短信接口(阿里云、腾讯云短信)
  31 +* 无缝整合第三方云存储(七牛云、阿里云OSS、又拍云)功能,支持云储存分片上传
  32 +* 第三方富文本编辑器支持(Summernote、Kindeditor、百度编辑器)
  33 +* 第三方登录(QQ、微信、微博)整合
  34 +* 第三方支付(微信、支付宝)无缝整合,微信支持PC端扫码支付
  35 +* 丰富的插件应用市场
  36 +
  37 +## 安装使用
  38 +
  39 +https://doc.fastadmin.net
  40 +
  41 +## 在线演示
  42 +
  43 +https://demo.fastadmin.net
  44 +
  45 +用户名:admin
  46 +
  47 +密 码:123456
  48 +
  49 +提 示:演示站数据无法进行修改,请下载源码安装体验全部功能
  50 +
  51 +## 界面截图
  52 +![控制台](https://images.gitee.com/uploads/images/2020/0929/202947_8db2d281_10933.gif "控制台")
  53 +
  54 +## 问题反馈
  55 +
  56 +在使用中有任何问题,请使用以下联系方式联系我们
  57 +
  58 +交流社区: https://ask.fastadmin.net
  59 +
  60 +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群) [749803490](https://jq.qq.com/?_wv=1027&k=5tczi88)(满) [767103006](https://jq.qq.com/?_wv=1027&k=5Z1U751)() [675115483](https://jq.qq.com/?_wv=1027&k=54I6mts)(6群)
  61 +
  62 +Github: https://github.com/karsonzhang/fastadmin
  63 +
  64 +Gitee: https://gitee.com/karson/fastadmin
  65 +
  66 +## 特别鸣谢
  67 +
  68 +感谢以下的项目,排名不分先后
  69 +
  70 +ThinkPHP:http://www.thinkphp.cn
  71 +
  72 +AdminLTE:https://adminlte.io
  73 +
  74 +Bootstrap:http://getbootstrap.com
  75 +
  76 +jQuery:http://jquery.com
  77 +
  78 +Bootstrap-table:https://github.com/wenzhixin/bootstrap-table
  79 +
  80 +Nice-validator: https://validator.niceue.com
  81 +
  82 +SelectPage: https://github.com/TerryZ/SelectPage
  83 +
  84 +Layer: https://layer.layui.com
  85 +
  86 +DropzoneJS: https://www.dropzonejs.com
  87 +
  88 +
  89 +## 版权信息
  90 +
  91 +FastAdmin遵循Apache2开源协议发布,并提供免费使用。
  92 +
  93 +本项目包含的第三方源码和二进制文件之版权信息另行标注。
  94 +
  95 +版权所有Copyright © 2017-2020 by FastAdmin (https://www.fastadmin.net)
  96 +
  97 +All rights reserved。
  1 +deny from all
  1 +<?php
  2 +
  3 +namespace app\admin\behavior;
  4 +
  5 +class AdminLog
  6 +{
  7 + public function run(&$params)
  8 + {
  9 + //只记录POST请求的日志
  10 + if (request()->isPost() && config('fastadmin.auto_record_log')) {
  11 + \app\admin\model\AdminLog::record();
  12 + }
  13 + }
  14 +}
  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' . DS) !== false) {
  38 + $name = explode(DS, $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) . ";\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 +];
  1 +<?php
  2 +
  3 +namespace addons\{%addon%}\controller;
  4 +
  5 +use think\addons\Controller;
  6 +
  7 +class Index extends Controller
  8 +{
  9 +
  10 + public function index()
  11 + {
  12 + $this->error("当前插件暂无前台页面");
  13 + }
  14 +
  15 +}
  1 +name = {%name%}
  2 +title = 插件名称{%name%}
  3 +intro = FastAdmin插件
  4 +author = yourname
  5 +website = https://www.fastadmin.net
  6 +version = 1.0.0
  7 +state = 1
  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 + 'sitename' => config('site.name'),
  100 + 'title' => $title,
  101 + 'author' => $author,
  102 + 'description' => '',
  103 + 'apiurl' => $url,
  104 + 'language' => $language,
  105 + ];
  106 + $builder = new Builder($classes);
  107 + $content = $builder->render($template_file, ['config' => $config, 'lang' => $lang]);
  108 +
  109 + if (!file_put_contents($output_file, $content)) {
  110 + throw new Exception('Cannot save the content to ' . $output_file);
  111 + }
  112 + $output->info("Build Successed!");
  113 + }
  114 +
  115 + /**
  116 + * get full qualified class name
  117 + *
  118 + * @param string $path_to_file
  119 + * @return string
  120 + * @author JBYRNE http://jarretbyrne.com/2015/06/197/
  121 + */
  122 + protected function get_class_from_file($path_to_file)
  123 + {
  124 + //Grab the contents of the file
  125 + $contents = file_get_contents($path_to_file);
  126 +
  127 + //Start with a blank namespace and class
  128 + $namespace = $class = "";
  129 +
  130 + //Set helper values to know that we have found the namespace/class token and need to collect the string values after them
  131 + $getting_namespace = $getting_class = false;
  132 +
  133 + //Go through each token and evaluate it as necessary
  134 + foreach (token_get_all($contents) as $token) {
  135 +
  136 + //If this token is the namespace declaring, then flag that the next tokens will be the namespace name
  137 + if (is_array($token) && $token[0] == T_NAMESPACE) {
  138 + $getting_namespace = true;
  139 + }
  140 +
  141 + //If this token is the class declaring, then flag that the next tokens will be the class name
  142 + if (is_array($token) && $token[0] == T_CLASS) {
  143 + $getting_class = true;
  144 + }
  145 +
  146 + //While we're grabbing the namespace name...
  147 + if ($getting_namespace === true) {
  148 +
  149 + //If the token is a string or the namespace separator...
  150 + if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) {
  151 +
  152 + //Append the token's value to the name of the namespace
  153 + $namespace .= $token[1];
  154 + } elseif ($token === ';') {
  155 +
  156 + //If the token is the semicolon, then we're done with the namespace declaration
  157 + $getting_namespace = false;
  158 + }
  159 + }
  160 +
  161 + //While we're grabbing the class name...
  162 + if ($getting_class === true) {
  163 +
  164 + //If the token is a string, it's the name of the class
  165 + if (is_array($token) && $token[0] == T_STRING) {
  166 +
  167 + //Store the token's value as the class name
  168 + $class = $token[1];
  169 +
  170 + //Got what we need, stope here
  171 + break;
  172 + }
  173 + }
  174 + }
  175 +
  176 + //Build the fully-qualified class name and return it
  177 + return $namespace ? $namespace . '\\' . $class : $class;
  178 + }
  179 +}
  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][$class . $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 + $docslist = array_filter($docslist , function($v) {return is_array($v) ; }) ;
  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 + <title>{$config.title}</title>
  9 +
  10 + <!-- Bootstrap Core CSS -->
  11 + <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  12 +
  13 + <!-- Plugin CSS -->
  14 + <link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  15 +
  16 + <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  17 + <!--[if lt IE 9]>
  18 + <script src="https://cdn.staticfile.org/html5shiv/3.7.3/html5shiv.min.js"></script>
  19 + <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
  20 + <![endif]-->
  21 +
  22 + <style type="text/css">
  23 + body {
  24 + padding-top: 70px; margin-bottom: 15px;
  25 + -webkit-font-smoothing: antialiased;
  26 + -moz-osx-font-smoothing: grayscale;
  27 + 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;
  28 + font-weight: 400;
  29 + }
  30 + h2 { font-size: 1.6em; }
  31 + hr { margin-top: 10px; }
  32 + .tab-pane { padding-top: 10px; }
  33 + .mt0 { margin-top: 0px; }
  34 + .footer { font-size: 12px; color: #666; }
  35 + .label { display: inline-block; min-width: 65px; padding: 0.3em 0.6em 0.3em; }
  36 + .string { color: green; }
  37 + .number { color: darkorange; }
  38 + .boolean { color: blue; }
  39 + .null { color: magenta; }
  40 + .key { color: red; }
  41 + .popover { max-width: 400px; max-height: 400px; overflow-y: auto;}
  42 + .list-group.panel > .list-group-item {
  43 + }
  44 + .list-group-item:last-child {
  45 + border-radius:0;
  46 + }
  47 + h4.panel-title a {
  48 + font-weight:normal;
  49 + font-size:14px;
  50 + }
  51 + h4.panel-title a .text-muted {
  52 + font-size:12px;
  53 + font-weight:normal;
  54 + font-family: 'Verdana';
  55 + }
  56 + #sidebar {
  57 + width: 220px;
  58 + position: fixed;
  59 + margin-left: -240px;
  60 + overflow-y:auto;
  61 + }
  62 + #sidebar > .list-group {
  63 + margin-bottom:0;
  64 + }
  65 + #sidebar > .list-group > a{
  66 + text-indent:0;
  67 + }
  68 + #sidebar .child {
  69 + border:1px solid #ddd;
  70 + border-bottom:none;
  71 + }
  72 + #sidebar .child > a {
  73 + border:0;
  74 + }
  75 + #sidebar .list-group a.current {
  76 + background:#f5f5f5;
  77 + }
  78 + @media (max-width: 1620px){
  79 + #sidebar {
  80 + margin:0;
  81 + }
  82 + #accordion {
  83 + padding-left:235px;
  84 + }
  85 + }
  86 + @media (max-width: 768px){
  87 + #sidebar {
  88 + display: none;
  89 + }
  90 + #accordion {
  91 + padding-left:0px;
  92 + }
  93 + }
  94 + .label-primary {
  95 + background-color: #248aff;
  96 + }
  97 +
  98 + </style>
  99 + </head>
  100 + <body>
  101 + <!-- Fixed navbar -->
  102 + <div class="navbar navbar-default navbar-fixed-top" role="navigation">
  103 + <div class="container">
  104 + <div class="navbar-header">
  105 + <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  106 + <span class="sr-only">Toggle navigation</span>
  107 + <span class="icon-bar"></span>
  108 + <span class="icon-bar"></span>
  109 + <span class="icon-bar"></span>
  110 + </button>
  111 + <a class="navbar-brand" href="./" target="_blank">{$config.title}</a>
  112 + </div>
  113 + <div class="navbar-collapse collapse">
  114 + <form class="navbar-form navbar-right">
  115 + <div class="form-group">
  116 + Token:
  117 + </div>
  118 + <div class="form-group">
  119 + <input type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Tokentips}" placeholder="token" id="token" />
  120 + </div>
  121 + <div class="form-group">
  122 + Apiurl:
  123 + </div>
  124 + <div class="form-group">
  125 + <input id="apiUrl" type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Apiurltips}" placeholder="https://api.mydomain.com" value="{$config.apiurl}" />
  126 + </div>
  127 + <div class="form-group">
  128 + <button type="button" class="btn btn-success btn-sm" data-toggle="tooltip" title="{$lang.Savetips}" id="save_data">
  129 + <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
  130 + </button>
  131 + </div>
  132 + </form>
  133 + </div><!--/.nav-collapse -->
  134 + </div>
  135 + </div>
  136 +
  137 + <div class="container">
  138 + <!-- menu -->
  139 + <div id="sidebar">
  140 + <div class="list-group panel">
  141 + {foreach name="docslist" id="docs"}
  142 + <a href="#{$key}" class="list-group-item" data-toggle="collapse" data-parent="#sidebar">{$key} <i class="fa fa-caret-down"></i></a>
  143 + <div class="child collapse" id="{$key}">
  144 + {foreach name="docs" id="api" }
  145 + <a href="javascript:;" data-id="{$api.id}" class="list-group-item">{$api.title}</a>
  146 + {/foreach}
  147 + </div>
  148 + {/foreach}
  149 + </div>
  150 + </div>
  151 + <div class="panel-group" id="accordion">
  152 + {foreach name="docslist" id="docs"}
  153 + <h2>{$key}</h2>
  154 + <hr>
  155 + {foreach name="docs" id="api" }
  156 + <div class="panel panel-default">
  157 + <div class="panel-heading" id="heading-{$api.id}">
  158 + <h4 class="panel-title">
  159 + <span class="label {$api.method_label}">{$api.method|strtoupper}</span>
  160 + <a data-toggle="collapse" data-parent="#accordion{$api.id}" href="#collapseOne{$api.id}"> {$api.title} <span class="text-muted">{$api.route}</span></a>
  161 + </h4>
  162 + </div>
  163 + <div id="collapseOne{$api.id}" class="panel-collapse collapse">
  164 + <div class="panel-body">
  165 +
  166 + <!-- Nav tabs -->
  167 + <ul class="nav nav-tabs" id="doctab{$api.id}">
  168 + <li class="active"><a href="#info{$api.id}" data-toggle="tab">{$lang.Info}</a></li>
  169 + <li><a href="#sandbox{$api.id}" data-toggle="tab">{$lang.Sandbox}</a></li>
  170 + <li><a href="#sample{$api.id}" data-toggle="tab">{$lang.Sampleoutput}</a></li>
  171 + </ul>
  172 +
  173 + <!-- Tab panes -->
  174 + <div class="tab-content">
  175 +
  176 + <div class="tab-pane active" id="info{$api.id}">
  177 + <div class="well">
  178 + {$api.summary}
  179 + </div>
  180 + <div class="panel panel-default">
  181 + <div class="panel-heading"><strong>{$lang.Headers}</strong></div>
  182 + <div class="panel-body">
  183 + {if $api.headerslist}
  184 + <table class="table table-hover">
  185 + <thead>
  186 + <tr>
  187 + <th>{$lang.Name}</th>
  188 + <th>{$lang.Type}</th>
  189 + <th>{$lang.Required}</th>
  190 + <th>{$lang.Description}</th>
  191 + </tr>
  192 + </thead>
  193 + <tbody>
  194 + {foreach name="api['headerslist']" id="header"}
  195 + <tr>
  196 + <td>{$header.name}</td>
  197 + <td>{$header.type}</td>
  198 + <td>{$header.required?'是':'否'}</td>
  199 + <td>{$header.description}</td>
  200 + </tr>
  201 + {/foreach}
  202 + </tbody>
  203 + </table>
  204 + {else /}
  205 +
  206 + {/if}
  207 + </div>
  208 + </div>
  209 + <div class="panel panel-default">
  210 + <div class="panel-heading"><strong>{$lang.Parameters}</strong></div>
  211 + <div class="panel-body">
  212 + {if $api.paramslist}
  213 + <table class="table table-hover">
  214 + <thead>
  215 + <tr>
  216 + <th>{$lang.Name}</th>
  217 + <th>{$lang.Type}</th>
  218 + <th>{$lang.Required}</th>
  219 + <th>{$lang.Description}</th>
  220 + </tr>
  221 + </thead>
  222 + <tbody>
  223 + {foreach name="api['paramslist']" id="param"}
  224 + <tr>
  225 + <td>{$param.name}</td>
  226 + <td>{$param.type}</td>
  227 + <td>{:$param.required?'是':'否'}</td>
  228 + <td>{$param.description}</td>
  229 + </tr>
  230 + {/foreach}
  231 + </tbody>
  232 + </table>
  233 + {else /}
  234 +
  235 + {/if}
  236 + </div>
  237 + </div>
  238 + <div class="panel panel-default">
  239 + <div class="panel-heading"><strong>{$lang.Body}</strong></div>
  240 + <div class="panel-body">
  241 + {$api.body|default='无'}
  242 + </div>
  243 + </div>
  244 + </div><!-- #info -->
  245 +
  246 + <div class="tab-pane" id="sandbox{$api.id}">
  247 + <div class="row">
  248 + <div class="col-md-12">
  249 + {if $api.headerslist}
  250 + <div class="panel panel-default">
  251 + <div class="panel-heading"><strong>{$lang.Headers}</strong></div>
  252 + <div class="panel-body">
  253 + <div class="headers">
  254 + {foreach name="api['headerslist']" id="param"}
  255 + <div class="form-group">
  256 + <label class="control-label" for="{$param.name}">{$param.name}</label>
  257 + <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}">
  258 + </div>
  259 + {/foreach}
  260 + </div>
  261 + </div>
  262 + </div>
  263 + {/if}
  264 + <div class="panel panel-default">
  265 + <div class="panel-heading"><strong>{$lang.Parameters}</strong></div>
  266 + <div class="panel-body">
  267 + <form enctype="application/x-www-form-urlencoded" role="form" action="{$api.route}" method="{$api.method}" name="form{$api.id}" id="form{$api.id}">
  268 + {if $api.paramslist}
  269 + {foreach name="api['paramslist']" id="param"}
  270 + <div class="form-group">
  271 + <label class="control-label" for="{$param.name}">{$param.name}</label>
  272 + <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}">
  273 + </div>
  274 + {/foreach}
  275 + {else /}
  276 + <div class="form-group">
  277 +
  278 + </div>
  279 + {/if}
  280 + <div class="form-group">
  281 + <button type="submit" class="btn btn-success send" rel="{$api.id}">{$lang.Send}</button>
  282 + <button type="reset" class="btn btn-info" rel="{$api.id}">{$lang.Reset}</button>
  283 + </div>
  284 + </form>
  285 + </div>
  286 + </div>
  287 + <div class="panel panel-default">
  288 + <div class="panel-heading"><strong>{$lang.Response}</strong></div>
  289 + <div class="panel-body">
  290 + <div class="row">
  291 + <div class="col-md-12" style="overflow-x:auto">
  292 + <pre id="response_headers{$api.id}"></pre>
  293 + <pre id="response{$api.id}"></pre>
  294 + </div>
  295 + </div>
  296 + </div>
  297 + </div>
  298 + <div class="panel panel-default">
  299 + <div class="panel-heading"><strong>{$lang.ReturnParameters}</strong></div>
  300 + <div class="panel-body">
  301 + {if $api.returnparamslist}
  302 + <table class="table table-hover">
  303 + <thead>
  304 + <tr>
  305 + <th>{$lang.Name}</th>
  306 + <th>{$lang.Type}</th>
  307 + <th>{$lang.Description}</th>
  308 + </tr>
  309 + </thead>
  310 + <tbody>
  311 + {foreach name="api['returnparamslist']" id="param"}
  312 + <tr>
  313 + <td>{$param.name}</td>
  314 + <td>{$param.type}</td>
  315 + <td>{$param.description}</td>
  316 + </tr>
  317 + {/foreach}
  318 + </tbody>
  319 + </table>
  320 + {else /}
  321 +
  322 + {/if}
  323 + </div>
  324 + </div>
  325 + </div>
  326 + </div>
  327 + </div><!-- #sandbox -->
  328 +
  329 + <div class="tab-pane" id="sample{$api.id}">
  330 + <div class="row">
  331 + <div class="col-md-12">
  332 + <pre id="sample_response{$api.id}">{$api.return|default='无'}</pre>
  333 + </div>
  334 + </div>
  335 + </div><!-- #sample -->
  336 +
  337 + </div><!-- .tab-content -->
  338 + </div>
  339 + </div>
  340 + </div>
  341 + {/foreach}
  342 + {/foreach}
  343 + </div>
  344 +
  345 + <hr>
  346 +
  347 + <div class="row mt0 footer">
  348 + <div class="col-md-6" align="left">
  349 + Generated on {:date('Y-m-d H:i:s')}
  350 + </div>
  351 + <div class="col-md-6" align="right">
  352 + <a href="./" target="_blank">{$config.sitename}</a>
  353 + </div>
  354 + </div>
  355 +
  356 + </div> <!-- /container -->
  357 +
  358 + <!-- jQuery -->
  359 + <script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
  360 +
  361 + <!-- Bootstrap Core JavaScript -->
  362 + <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
  363 +
  364 + <script type="text/javascript">
  365 + function syntaxHighlight(json) {
  366 + if (typeof json != 'string') {
  367 + json = JSON.stringify(json, undefined, 2);
  368 + }
  369 + json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  370 + return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
  371 + var cls = 'number';
  372 + if (/^"/.test(match)) {
  373 + if (/:$/.test(match)) {
  374 + cls = 'key';
  375 + } else {
  376 + cls = 'string';
  377 + }
  378 + } else if (/true|false/.test(match)) {
  379 + cls = 'boolean';
  380 + } else if (/null/.test(match)) {
  381 + cls = 'null';
  382 + }
  383 + return '<span class="' + cls + '">' + match + '</span>';
  384 + });
  385 + }
  386 +
  387 + function prepareStr(str) {
  388 + try {
  389 + return syntaxHighlight(JSON.stringify(JSON.parse(str.replace(/'/g, '"')), null, 2));
  390 + } catch (e) {
  391 + return str;
  392 + }
  393 + }
  394 + var storage = (function () {
  395 + var uid = new Date;
  396 + var storage;
  397 + var result;
  398 + try {
  399 + (storage = window.localStorage).setItem(uid, uid);
  400 + result = storage.getItem(uid) == uid;
  401 + storage.removeItem(uid);
  402 + return result && storage;
  403 + } catch (exception) {
  404 + }
  405 + }());
  406 +
  407 + $.fn.serializeObject = function ()
  408 + {
  409 + var o = {};
  410 + var a = this.serializeArray();
  411 + $.each(a, function () {
  412 + if (!this.value) {
  413 + return;
  414 + }
  415 + if (o[this.name] !== undefined) {
  416 + if (!o[this.name].push) {
  417 + o[this.name] = [o[this.name]];
  418 + }
  419 + o[this.name].push(this.value || '');
  420 + } else {
  421 + o[this.name] = this.value || '';
  422 + }
  423 + });
  424 + return o;
  425 + };
  426 +
  427 + $(document).ready(function () {
  428 +
  429 + if (storage) {
  430 + storage.getItem('token') && $('#token').val(storage.getItem('token'));
  431 + storage.getItem('apiUrl') && $('#apiUrl').val(storage.getItem('apiUrl'));
  432 + }
  433 +
  434 + $('[data-toggle="tooltip"]').tooltip({
  435 + placement: 'bottom'
  436 + });
  437 +
  438 + $(window).on("resize", function(){
  439 + $("#sidebar").css("max-height", $(window).height()-80);
  440 + });
  441 +
  442 + $(window).trigger("resize");
  443 +
  444 + $(document).on("click", "#sidebar .list-group > .list-group-item", function(){
  445 + $("#sidebar .list-group > .list-group-item").removeClass("current");
  446 + $(this).addClass("current");
  447 + });
  448 + $(document).on("click", "#sidebar .child a", function(){
  449 + var heading = $("#heading-"+$(this).data("id"));
  450 + if(!heading.next().hasClass("in")){
  451 + $("a", heading).trigger("click");
  452 + }
  453 + $("html,body").animate({scrollTop:heading.offset().top-70});
  454 + });
  455 +
  456 + $('code[id^=response]').hide();
  457 +
  458 + $.each($('pre[id^=sample_response],pre[id^=sample_post_body]'), function () {
  459 + if ($(this).html() == 'NA') {
  460 + return;
  461 + }
  462 + var str = prepareStr($(this).html());
  463 + $(this).html(str);
  464 + });
  465 +
  466 + $("[data-toggle=popover]").popover({placement: 'right'});
  467 +
  468 + $('[data-toggle=popover]').on('shown.bs.popover', function () {
  469 + var $sample = $(this).parent().find(".popover-content"),
  470 + str = $(this).data('content');
  471 + if (typeof str == "undefined" || str === "") {
  472 + return;
  473 + }
  474 + var str = prepareStr(str);
  475 + $sample.html('<pre>' + str + '</pre>');
  476 + });
  477 +
  478 + $('body').on('click', '#save_data', function (e) {
  479 + if (storage) {
  480 + storage.setItem('token', $('#token').val());
  481 + storage.setItem('apiUrl', $('#apiUrl').val());
  482 + } else {
  483 + alert('Your browser does not support local storage');
  484 + }
  485 + });
  486 +
  487 + $('body').on('click', '.send', function (e) {
  488 + e.preventDefault();
  489 + var form = $(this).closest('form');
  490 + //added /g to get all the matched params instead of only first
  491 + var matchedParamsInRoute = $(form).attr('action').match(/[^{]+(?=\})/g);
  492 + var theId = $(this).attr('rel');
  493 + //keep a copy of action attribute in order to modify the copy
  494 + //instead of the initial attribute
  495 + var url = $(form).attr('action');
  496 + var method = $(form).prop('method').toLowerCase() || 'get';
  497 +
  498 + var formData = new FormData();
  499 +
  500 + $(form).find('input').each(function (i, input) {
  501 + if ($(input).attr('type').toLowerCase() == 'file') {
  502 + formData.append($(input).attr('name'), $(input)[0].files[0]);
  503 + method = 'post';
  504 + } else {
  505 + formData.append($(input).attr('name'), $(input).val())
  506 + }
  507 + });
  508 +
  509 + var index, key, value;
  510 +
  511 + if (matchedParamsInRoute) {
  512 + var params = {};
  513 + formData.forEach(function(value, key){
  514 + params[key] = value;
  515 + });
  516 + for (index = 0; index < matchedParamsInRoute.length; ++index) {
  517 + try {
  518 + key = matchedParamsInRoute[index];
  519 + value = params[key];
  520 + if (typeof value == "undefined")
  521 + value = "";
  522 + url = url.replace("\{" + key + "\}", value);
  523 + formData.delete(key);
  524 + } catch (err) {
  525 + console.log(err);
  526 + }
  527 + }
  528 + }
  529 +
  530 + var headers = {};
  531 +
  532 + var token = $('#token').val();
  533 + if (token.length > 0) {
  534 + headers['token'] = token;
  535 + }
  536 +
  537 + $("#sandbox" + theId + " .headers input[type=text]").each(function () {
  538 + val = $(this).val();
  539 + if (val.length > 0) {
  540 + headers[$(this).prop('name')] = val;
  541 + }
  542 + });
  543 +
  544 + $.ajax({
  545 + url: $('#apiUrl').val() + url,
  546 + data: method == 'get' ? $(form).serialize() : formData,
  547 + type: method,
  548 + dataType: 'json',
  549 + contentType: false,
  550 + processData: false,
  551 + headers: headers,
  552 + xhrFields: {
  553 + withCredentials: true
  554 + },
  555 + success: function (data, textStatus, xhr) {
  556 + if (typeof data === 'object') {
  557 + var str = JSON.stringify(data, null, 2);
  558 + $('#response' + theId).html(syntaxHighlight(str));
  559 + } else {
  560 + $('#response' + theId).html(data || '');
  561 + }
  562 + $('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders());
  563 + $('#response' + theId).show();
  564 + },
  565 + error: function (xhr, textStatus, error) {
  566 + try {
  567 + var str = JSON.stringify($.parseJSON(xhr.responseText), null, 2);
  568 + } catch (e) {
  569 + var str = xhr.responseText;
  570 + }
  571 + $('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders());
  572 + $('#response' + theId).html(syntaxHighlight(str));
  573 + $('#response' + theId).show();
  574 + }
  575 + });
  576 + return false;
  577 + });
  578 + });
  579 + </script>
  580 + </body>
  581 +</html>
  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 + $relationModels = $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($relationModels[$index]) ? $relationModels[$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 + //继续删除菜单
  444 + if ($menu) {
  445 + exec("php think menu -c {$controllerUrl} -d 1 -f 1");
  446 + }
  447 +
  448 + $output->info("Delete Successed");
  449 + return;
  450 + }
  451 +
  452 + //非覆盖模式时如果存在控制器文件则报错
  453 + if (is_file($controllerFile) && !$force) {
  454 + throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  455 + }
  456 +
  457 + //非覆盖模式时如果存在模型文件则报错
  458 + if (is_file($modelFile) && !$force) {
  459 + throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  460 + }
  461 +
  462 + //非覆盖模式时如果存在验证文件则报错
  463 + if (is_file($validateFile) && !$force) {
  464 + throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  465 + }
  466 +
  467 + require $adminPath . 'common.php';
  468 +
  469 + //从数据库中获取表字段信息
  470 + $sql = "SELECT * FROM `information_schema`.`columns` "
  471 + . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  472 + . "ORDER BY ORDINAL_POSITION";
  473 + //加载主表的列
  474 + $columnList = $dbconnect->query($sql, [$dbname, $modelTableName]);
  475 + $fieldArr = [];
  476 + foreach ($columnList as $k => $v) {
  477 + $fieldArr[] = $v['COLUMN_NAME'];
  478 + }
  479 +
  480 + // 加载关联表的列
  481 + foreach ($relations as $index => &$relation) {
  482 + $relationColumnList = $dbconnect->query($sql, [$dbname, $relation['relationTableName']]);
  483 +
  484 + $relationFieldList = [];
  485 + foreach ($relationColumnList as $k => $v) {
  486 + $relationFieldList[] = $v['COLUMN_NAME'];
  487 + }
  488 + if (!$relation['relationPrimaryKey']) {
  489 + foreach ($relationColumnList as $k => $v) {
  490 + if ($v['COLUMN_KEY'] == 'PRI') {
  491 + $relation['relationPrimaryKey'] = $v['COLUMN_NAME'];
  492 + break;
  493 + }
  494 + }
  495 + }
  496 + // 如果主键为空
  497 + if (!$relation['relationPrimaryKey']) {
  498 + throw new Exception('Relation Primary key not found!');
  499 + }
  500 + // 如果主键不在表字段中
  501 + if (!in_array($relation['relationPrimaryKey'], $relationFieldList)) {
  502 + throw new Exception('Relation Primary key not found in table!');
  503 + }
  504 + $relation['relationColumnList'] = $relationColumnList;
  505 + $relation['relationFieldList'] = $relationFieldList;
  506 + }
  507 + unset($relation);
  508 +
  509 + $addList = [];
  510 + $editList = [];
  511 + $javascriptList = [];
  512 + $langList = [];
  513 + $field = 'id';
  514 + $order = 'id';
  515 + $priDefined = false;
  516 + $priKey = '';
  517 + $relationPrimaryKey = '';
  518 + foreach ($columnList as $k => $v) {
  519 + if ($v['COLUMN_KEY'] == 'PRI') {
  520 + $priKey = $v['COLUMN_NAME'];
  521 + break;
  522 + }
  523 + }
  524 + if (!$priKey) {
  525 + throw new Exception('Primary key not found!');
  526 + }
  527 +
  528 + $order = $priKey;
  529 +
  530 + //如果是关联模型
  531 + foreach ($relations as $index => &$relation) {
  532 + if ($relation['relationMode'] == 'hasone') {
  533 + $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id";
  534 + $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  535 +
  536 + if (!in_array($relationForeignKey, $relation['relationFieldList'])) {
  537 + throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']');
  538 + }
  539 + if (!in_array($relationPrimaryKey, $fieldArr)) {
  540 + throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']');
  541 + }
  542 + } else {
  543 + $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id";
  544 + $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey'];
  545 + if (!in_array($relationForeignKey, $fieldArr)) {
  546 + throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']');
  547 + }
  548 + if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) {
  549 + throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']');
  550 + }
  551 + }
  552 + $relation['relationForeignKey'] = $relationForeignKey;
  553 + $relation['relationPrimaryKey'] = $relationPrimaryKey;
  554 + $relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName'];
  555 + }
  556 + unset($relation);
  557 +
  558 + try {
  559 + Form::setEscapeHtml(false);
  560 + $setAttrArr = [];
  561 + $getAttrArr = [];
  562 + $getEnumArr = [];
  563 + $appendAttrList = [];
  564 + $controllerAssignList = [];
  565 + $headingHtml = '{:build_heading()}';
  566 + $recyclebinHtml = '';
  567 +
  568 + //循环所有字段,开始构造视图的HTML和JS信息
  569 + foreach ($columnList as $k => $v) {
  570 + $field = $v['COLUMN_NAME'];
  571 + $itemArr = [];
  572 + // 这里构建Enum和Set类型的列表数据
  573 + if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
  574 + if ($v['DATA_TYPE'] !== 'tinyint') {
  575 + $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  576 + $itemArr = explode(',', str_replace("'", '', $itemArr));
  577 + }
  578 + $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  579 + //如果类型为tinyint且有使用备注数据
  580 + if ($itemArr && $v['DATA_TYPE'] == 'tinyint') {
  581 + $v['DATA_TYPE'] = 'enum';
  582 + }
  583 + }
  584 + // 语言列表
  585 + if ($v['COLUMN_COMMENT'] != '') {
  586 + $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  587 + }
  588 + $inputType = '';
  589 + //保留字段不能修改和添加
  590 + if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) {
  591 + $inputType = $this->getFieldType($v);
  592 +
  593 + // 如果是number类型时增加一个步长
  594 + $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  595 +
  596 + $attrArr = ['id' => "c-{$field}"];
  597 + $cssClassArr = ['form-control'];
  598 + $fieldName = "row[{$field}]";
  599 + $defaultValue = $v['COLUMN_DEFAULT'];
  600 + $editValue = "{\$row.{$field}|htmlentities}";
  601 + // 如果默认值非null,则是一个必选项
  602 + if ($v['IS_NULLABLE'] == 'NO') {
  603 + $attrArr['data-rule'] = 'required';
  604 + }
  605 +
  606 + if ($inputType == 'select') {
  607 + $cssClassArr[] = 'selectpicker';
  608 + $attrArr['class'] = implode(' ', $cssClassArr);
  609 + if ($v['DATA_TYPE'] == 'set') {
  610 + $attrArr['multiple'] = '';
  611 + $fieldName .= "[]";
  612 + }
  613 + $attrArr['name'] = $fieldName;
  614 +
  615 + $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  616 +
  617 + $itemArr = $this->getLangArray($itemArr, false);
  618 + //添加一个获取器
  619 + $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  620 + if ($v['DATA_TYPE'] == 'set') {
  621 + $this->setAttr($setAttrArr, $field, $inputType);
  622 + }
  623 + $this->appendAttr($appendAttrList, $field);
  624 + $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  625 + $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  626 + } elseif ($inputType == 'datetime') {
  627 + $cssClassArr[] = 'datetimepicker';
  628 + $attrArr['class'] = implode(' ', $cssClassArr);
  629 + $format = "YYYY-MM-DD HH:mm:ss";
  630 + $phpFormat = "Y-m-d H:i:s";
  631 + $fieldFunc = '';
  632 + switch ($v['DATA_TYPE']) {
  633 + case 'year':
  634 + $format = "YYYY";
  635 + $phpFormat = 'Y';
  636 + break;
  637 + case 'date':
  638 + $format = "YYYY-MM-DD";
  639 + $phpFormat = 'Y-m-d';
  640 + break;
  641 + case 'time':
  642 + $format = "HH:mm:ss";
  643 + $phpFormat = 'H:i:s';
  644 + break;
  645 + case 'timestamp':
  646 + $fieldFunc = 'datetime';
  647 + // no break
  648 + case 'datetime':
  649 + $format = "YYYY-MM-DD HH:mm:ss";
  650 + $phpFormat = 'Y-m-d H:i:s';
  651 + break;
  652 + default:
  653 + $fieldFunc = 'datetime';
  654 + $this->getAttr($getAttrArr, $field, $inputType);
  655 + $this->setAttr($setAttrArr, $field, $inputType);
  656 + $this->appendAttr($appendAttrList, $field);
  657 + break;
  658 + }
  659 + $defaultDateTime = "{:date('{$phpFormat}')}";
  660 + $attrArr['data-date-format'] = $format;
  661 + $attrArr['data-use-current'] = "true";
  662 + $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  663 + $formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr);
  664 + } elseif ($inputType == 'checkbox' || $inputType == 'radio') {
  665 + unset($attrArr['data-rule']);
  666 + $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
  667 + $attrArr['name'] = "row[{$fieldName}]";
  668 +
  669 + $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
  670 + $itemArr = $this->getLangArray($itemArr, false);
  671 + //添加一个获取器
  672 + $this->getAttr($getAttrArr, $field, $inputType);
  673 + if ($inputType == 'checkbox') {
  674 + $this->setAttr($setAttrArr, $field, $inputType);
  675 + }
  676 + $this->appendAttr($appendAttrList, $field);
  677 + $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
  678 +
  679 + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  680 + $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  681 + } elseif ($inputType == 'textarea' && !$this->isMatchSuffix($field, $this->selectpagesSuffix) && !$this->isMatchSuffix($field, $this->imageField)) {
  682 + $cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : '';
  683 + $attrArr['class'] = implode(' ', $cssClassArr);
  684 + $attrArr['rows'] = 5;
  685 + $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  686 + $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  687 + } elseif ($inputType == 'switch') {
  688 + unset($attrArr['data-rule']);
  689 + if ($defaultValue === '1' || $defaultValue === 'Y') {
  690 + $yes = $defaultValue;
  691 + $no = $defaultValue === '1' ? '0' : 'N';
  692 + } else {
  693 + $no = $defaultValue;
  694 + $yes = $defaultValue === '0' ? '1' : 'Y';
  695 + }
  696 + if (!$itemArr) {
  697 + $itemArr = [$yes => 'Yes', $no => 'No'];
  698 + }
  699 + $stateNoClass = 'fa-flip-horizontal text-gray';
  700 + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
  701 + $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}"]);
  702 + } elseif ($inputType == 'citypicker') {
  703 + $attrArr['class'] = implode(' ', $cssClassArr);
  704 + $attrArr['data-toggle'] = "city-picker";
  705 + $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
  706 + $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
  707 + } elseif ($inputType == 'fieldlist') {
  708 + $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  709 + $itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key';
  710 + $itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value';
  711 + $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $defaultValue]);
  712 + $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $editValue]);
  713 + } else {
  714 + $search = $replace = '';
  715 + //特殊字段为关联搜索
  716 + if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
  717 + $inputType = 'text';
  718 + $defaultValue = '';
  719 + $attrArr['data-rule'] = 'required';
  720 + $cssClassArr[] = 'selectpage';
  721 + $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
  722 + $attrArr['data-source'] = $selectpageController . "/index";
  723 + //如果是类型表需要特殊处理下
  724 + if ($selectpageController == 'category') {
  725 + $attrArr['data-source'] = 'category/selectpage';
  726 + $attrArr['data-params'] = '##replacetext##';
  727 + $search = '"##replacetext##"';
  728 + $replace = '\'{"custom[type]":"' . $table . '"}\'';
  729 + } elseif ($selectpageController == 'admin') {
  730 + $attrArr['data-source'] = 'auth/admin/selectpage';
  731 + } elseif ($selectpageController == 'user') {
  732 + $attrArr['data-source'] = 'user/user/index';
  733 + }
  734 + if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
  735 + $attrArr['data-multiple'] = 'true';
  736 + }
  737 + foreach ($this->fieldSelectpageMap as $m => $n) {
  738 + if (in_array($field, $n)) {
  739 + $attrArr['data-field'] = $m;
  740 + break;
  741 + }
  742 + }
  743 + }
  744 + //因为有自动完成可输入其它内容
  745 + $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  746 + $attrArr['class'] = implode(' ', $cssClassArr);
  747 + $isUpload = false;
  748 + if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
  749 + $isUpload = true;
  750 + }
  751 + //如果是步长则加上步长
  752 + if ($step) {
  753 + $attrArr['step'] = $step;
  754 + }
  755 + //如果是图片加上个size
  756 + if ($isUpload) {
  757 + $attrArr['size'] = 50;
  758 + }
  759 +
  760 + $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  761 + $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  762 + if ($search && $replace) {
  763 + $formAddElement = str_replace($search, $replace, $formAddElement);
  764 + $formEditElement = str_replace($search, $replace, $formEditElement);
  765 + }
  766 + //如果是图片或文件
  767 + if ($isUpload) {
  768 + $formAddElement = $this->getImageUpload($field, $formAddElement);
  769 + $formEditElement = $this->getImageUpload($field, $formEditElement);
  770 + }
  771 + }
  772 + //构造添加和编辑HTML信息
  773 + $addList[] = $this->getFormGroup($field, $formAddElement);
  774 + $editList[] = $this->getFormGroup($field, $formEditElement);
  775 + }
  776 +
  777 + //过滤text类型字段
  778 + if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
  779 + //主键
  780 + if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
  781 + $priDefined = true;
  782 + $javascriptList[] = "{checkbox: true}";
  783 + }
  784 + if ($this->deleteTimeField == $field) {
  785 + $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
  786 + continue;
  787 + }
  788 + if (!$fields || in_array($field, explode(',', $fields))) {
  789 + //构造JS列信息
  790 + $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  791 + }
  792 + if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
  793 + $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
  794 + }
  795 + //排序方式,如果有指定排序字段,否则按主键排序
  796 + $order = $field == $this->sortField ? $this->sortField : $order;
  797 + }
  798 + }
  799 +
  800 + //循环关联表,追加语言包和JS列
  801 + foreach ($relations as $index => $relation) {
  802 + foreach ($relation['relationColumnList'] as $k => $v) {
  803 + // 不显示的字段直接过滤掉
  804 + if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  805 + continue;
  806 + }
  807 +
  808 + $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  809 + // 语言列表
  810 + if ($v['COLUMN_COMMENT'] != '') {
  811 + $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  812 + }
  813 +
  814 + //过滤text类型字段
  815 + if ($v['DATA_TYPE'] != 'text') {
  816 + //构造JS列信息
  817 + $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  818 + }
  819 + }
  820 + }
  821 +
  822 + //JS最后一列加上操作列
  823 + $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  824 + $addList = implode("\n", array_filter($addList));
  825 + $editList = implode("\n", array_filter($editList));
  826 + $javascriptList = implode(",\n", array_filter($javascriptList));
  827 + $langList = implode(",\n", array_filter($langList));
  828 + //数组等号对齐
  829 + $langList = array_filter(explode(",\n", $langList . ",\n"));
  830 + foreach ($langList as &$line) {
  831 + if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
  832 + $line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
  833 + }
  834 + }
  835 + unset($line);
  836 + $langList = implode(",\n", array_filter($langList));
  837 +
  838 + //表注释
  839 + $tableComment = $modelTableInfo['Comment'];
  840 + $tableComment = mb_substr($tableComment, -1) == '' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  841 +
  842 + $modelInit = '';
  843 + if ($priKey != $order) {
  844 + $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  845 + }
  846 +
  847 + $data = [
  848 + 'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';",
  849 + 'controllerNamespace' => $controllerNamespace,
  850 + 'modelNamespace' => $modelNamespace,
  851 + 'validateNamespace' => $validateNamespace,
  852 + 'controllerUrl' => $controllerUrl,
  853 + 'controllerName' => $controllerName,
  854 + 'controllerAssignList' => implode("\n", $controllerAssignList),
  855 + 'modelName' => $modelName,
  856 + 'modelTableName' => $modelTableName,
  857 + 'modelTableType' => $modelTableType,
  858 + 'modelTableTypeName' => $modelTableTypeName,
  859 + 'validateName' => $validateName,
  860 + 'tableComment' => $tableComment,
  861 + 'iconName' => $iconName,
  862 + 'pk' => $priKey,
  863 + 'order' => $order,
  864 + 'table' => $table,
  865 + 'tableName' => $modelTableName,
  866 + 'addList' => $addList,
  867 + 'editList' => $editList,
  868 + 'javascriptList' => $javascriptList,
  869 + 'langList' => $langList,
  870 + 'sofeDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
  871 + 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  872 + 'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false',
  873 + 'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
  874 + 'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
  875 + 'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
  876 + 'relationSearch' => $relations ? 'true' : 'false',
  877 + 'relationWithList' => '',
  878 + 'relationMethodList' => '',
  879 + 'controllerIndex' => '',
  880 + 'recyclebinJs' => '',
  881 + 'headingHtml' => $headingHtml,
  882 + 'recyclebinHtml' => $recyclebinHtml,
  883 + 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '',
  884 + 'appendAttrList' => implode(",\n", $appendAttrList),
  885 + 'getEnumList' => implode("\n\n", $getEnumArr),
  886 + 'getAttrList' => implode("\n\n", $getAttrArr),
  887 + 'setAttrList' => implode("\n\n", $setAttrArr),
  888 + 'modelInit' => $modelInit,
  889 + ];
  890 +
  891 + //如果使用关联模型
  892 + if ($relations) {
  893 + $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  894 + foreach ($relations as $index => $relation) {
  895 + //需要构造关联的方法
  896 + $relation['relationMethod'] = strtolower($relation['relationName']);
  897 +
  898 + //关联的模式
  899 + $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
  900 +
  901 + //关联字段
  902 + $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  903 +
  904 + //预载入的方法
  905 + $relationWithList[] = $relation['relationMethod'];
  906 +
  907 + unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  908 +
  909 + //构造关联模型的方法
  910 + $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
  911 +
  912 + //如果设置了显示主表字段,则必须显式将关联表字段显示
  913 + if ($fields) {
  914 + $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
  915 + }
  916 +
  917 + //显示的字段
  918 + if ($relation['relationFields']) {
  919 + $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  920 + }
  921 + }
  922 +
  923 + $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  924 + $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  925 + $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  926 +
  927 + //需要重写index方法
  928 + $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  929 + } elseif ($fields) {
  930 + $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  931 + //需要重写index方法
  932 + $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  933 + }
  934 +
  935 + // 生成控制器文件
  936 + $this->writeToFile('controller', $data, $controllerFile);
  937 + // 生成模型文件
  938 + $this->writeToFile('model', $data, $modelFile);
  939 +
  940 + if ($relations) {
  941 + foreach ($relations as $i => $relation) {
  942 + $relation['modelNamespace'] = $data['modelNamespace'];
  943 + if (!is_file($relation['relationFile'])) {
  944 + // 生成关联模型文件
  945 + $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  946 + }
  947 + }
  948 + }
  949 + // 生成验证文件
  950 + $this->writeToFile('validate', $data, $validateFile);
  951 + // 生成视图文件
  952 + $this->writeToFile('add', $data, $addFile);
  953 + $this->writeToFile('edit', $data, $editFile);
  954 + $this->writeToFile('index', $data, $indexFile);
  955 + if ($recyclebinHtml) {
  956 + $this->writeToFile('recyclebin', $data, $recyclebinFile);
  957 + $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
  958 + $recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
  959 + $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
  960 + }
  961 + // 生成JS文件
  962 + $this->writeToFile('javascript', $data, $javascriptFile);
  963 + // 生成语言文件
  964 + $this->writeToFile('lang', $data, $langFile);
  965 + } catch (ErrorException $e) {
  966 + throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  967 + }
  968 +
  969 + //继续生成菜单
  970 + if ($menu) {
  971 + exec("php think menu -c {$controllerUrl}");
  972 + }
  973 +
  974 + $output->info("Build Successed");
  975 + }
  976 +
  977 + protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  978 + {
  979 + if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  980 + return;
  981 + }
  982 + $fieldList = $this->getFieldListName($field);
  983 + $methodName = 'get' . ucfirst($fieldList);
  984 + foreach ($itemArr as $k => &$v) {
  985 + $v = "__('" . mb_ucfirst($v) . "')";
  986 + }
  987 + unset($v);
  988 + $itemString = $this->getArrayString($itemArr);
  989 + $getEnum[] = <<<EOD
  990 + public function {$methodName}()
  991 + {
  992 + return [{$itemString}];
  993 + }
  994 +EOD;
  995 + $controllerAssignList[] = <<<EOD
  996 + \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  997 +EOD;
  998 + }
  999 +
  1000 + protected function getAttr(&$getAttr, $field, $inputType = '')
  1001 + {
  1002 + if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1003 + return;
  1004 + }
  1005 + $attrField = ucfirst($this->getCamelizeName($field));
  1006 + $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  1007 + }
  1008 +
  1009 + protected function setAttr(&$setAttr, $field, $inputType = '')
  1010 + {
  1011 + if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
  1012 + return;
  1013 + }
  1014 + $attrField = ucfirst($this->getCamelizeName($field));
  1015 + if ($inputType == 'datetime') {
  1016 + $return = <<<EOD
  1017 +return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  1018 +EOD;
  1019 + } elseif (in_array($inputType, ['checkbox', 'select'])) {
  1020 + $return = <<<EOD
  1021 +return is_array(\$value) ? implode(',', \$value) : \$value;
  1022 +EOD;
  1023 + }
  1024 + $setAttr[] = <<<EOD
  1025 + protected function set{$attrField}Attr(\$value)
  1026 + {
  1027 + $return
  1028 + }
  1029 +EOD;
  1030 + }
  1031 +
  1032 + protected function appendAttr(&$appendAttrList, $field)
  1033 + {
  1034 + $appendAttrList[] = <<<EOD
  1035 + '{$field}_text'
  1036 +EOD;
  1037 + }
  1038 +
  1039 + /**
  1040 + * 移除相对的空目录
  1041 + * @param $parseFile
  1042 + * @param $parseArr
  1043 + * @return bool
  1044 + */
  1045 + protected function removeEmptyBaseDir($parseFile, $parseArr)
  1046 + {
  1047 + if (count($parseArr) > 1) {
  1048 + $parentDir = dirname($parseFile);
  1049 + for ($i = 0; $i < count($parseArr); $i++) {
  1050 + try {
  1051 + $iterator = new \FilesystemIterator($parentDir);
  1052 + $isDirEmpty = !$iterator->valid();
  1053 + if ($isDirEmpty) {
  1054 + rmdir($parentDir);
  1055 + $parentDir = dirname($parentDir);
  1056 + } else {
  1057 + return true;
  1058 + }
  1059 + } catch (\UnexpectedValueException $e) {
  1060 + return false;
  1061 + }
  1062 + }
  1063 + }
  1064 + return true;
  1065 + }
  1066 +
  1067 + /**
  1068 + * 获取控制器相关信息
  1069 + * @param $module
  1070 + * @param $controller
  1071 + * @param $table
  1072 + * @return array
  1073 + */
  1074 + protected function getControllerData($module, $controller, $table)
  1075 + {
  1076 + return $this->getParseNameData($module, $controller, $table, 'controller');
  1077 + }
  1078 +
  1079 + /**
  1080 + * 获取模型相关信息
  1081 + * @param $module
  1082 + * @param $model
  1083 + * @param $table
  1084 + * @return array
  1085 + */
  1086 + protected function getModelData($module, $model, $table)
  1087 + {
  1088 + return $this->getParseNameData($module, $model, $table, 'model');
  1089 + }
  1090 +
  1091 + /**
  1092 + * 获取验证器相关信息
  1093 + * @param $module
  1094 + * @param $validate
  1095 + * @param $table
  1096 + * @return array
  1097 + */
  1098 + protected function getValidateData($module, $validate, $table)
  1099 + {
  1100 + return $this->getParseNameData($module, $validate, $table, 'validate');
  1101 + }
  1102 +
  1103 + /**
  1104 + * 获取已解析相关信息
  1105 + * @param string $module 模块名称
  1106 + * @param string $name 自定义名称
  1107 + * @param string $table 数据表名
  1108 + * @param string $type 解析类型,本例中为controller、model、validate
  1109 + * @return array
  1110 + */
  1111 + protected function getParseNameData($module, $name, $table, $type)
  1112 + {
  1113 + $arr = [];
  1114 + if (!$name) {
  1115 + $parseName = Loader::parseName($table, 1);
  1116 + $parseArr = [$table];
  1117 + } else {
  1118 + $name = str_replace(['.', '/', '\\'], '/', $name);
  1119 + $arr = explode('/', $name);
  1120 + $parseName = ucfirst(array_pop($arr));
  1121 + $parseArr = $arr;
  1122 + array_push($parseArr, $parseName);
  1123 + }
  1124 + //类名不能为内部关键字
  1125 + if (in_array(strtolower($parseName), $this->internalKeywords)) {
  1126 + throw new Exception('Unable to use internal variable:' . $parseName);
  1127 + }
  1128 + $appNamespace = Config::get('app_namespace');
  1129 + $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
  1130 + $moduleDir = APP_PATH . $module . DS;
  1131 + $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  1132 + return [$parseNamespace, $parseName, $parseFile, $parseArr];
  1133 + }
  1134 +
  1135 + /**
  1136 + * 写入到文件
  1137 + * @param string $name
  1138 + * @param array $data
  1139 + * @param string $pathname
  1140 + * @return mixed
  1141 + */
  1142 + protected function writeToFile($name, $data, $pathname)
  1143 + {
  1144 + foreach ($data as $index => &$datum) {
  1145 + $datum = is_array($datum) ? '' : $datum;
  1146 + }
  1147 + unset($datum);
  1148 + $content = $this->getReplacedStub($name, $data);
  1149 +
  1150 + if (!is_dir(dirname($pathname))) {
  1151 + mkdir(dirname($pathname), 0755, true);
  1152 + }
  1153 + return file_put_contents($pathname, $content);
  1154 + }
  1155 +
  1156 + /**
  1157 + * 获取替换后的数据
  1158 + * @param string $name
  1159 + * @param array $data
  1160 + * @return string
  1161 + */
  1162 + protected function getReplacedStub($name, $data)
  1163 + {
  1164 + foreach ($data as $index => &$datum) {
  1165 + $datum = is_array($datum) ? '' : $datum;
  1166 + }
  1167 + unset($datum);
  1168 + $search = $replace = [];
  1169 + foreach ($data as $k => $v) {
  1170 + $search[] = "{%{$k}%}";
  1171 + $replace[] = $v;
  1172 + }
  1173 + $stubname = $this->getStub($name);
  1174 + if (isset($this->stubList[$stubname])) {
  1175 + $stub = $this->stubList[$stubname];
  1176 + } else {
  1177 + $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  1178 + }
  1179 + $content = str_replace($search, $replace, $stub);
  1180 + return $content;
  1181 + }
  1182 +
  1183 + /**
  1184 + * 获取基础模板
  1185 + * @param string $name
  1186 + * @return string
  1187 + */
  1188 + protected function getStub($name)
  1189 + {
  1190 + return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  1191 + }
  1192 +
  1193 + protected function getLangItem($field, $content)
  1194 + {
  1195 + if ($content || !Lang::has($field)) {
  1196 + $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
  1197 + $content = str_replace(',', ',', $content);
  1198 + if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
  1199 + list($fieldLang, $item) = explode(':', $content);
  1200 + $itemArr = [$field => $fieldLang];
  1201 + foreach (explode(',', $item) as $k => $v) {
  1202 + $valArr = explode('=', $v);
  1203 + if (count($valArr) == 2) {
  1204 + list($key, $value) = $valArr;
  1205 + $itemArr[$field . ' ' . $key] = $value;
  1206 + $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
  1207 + }
  1208 + }
  1209 + } else {
  1210 + $itemArr = [$field => $content];
  1211 + }
  1212 + $resultArr = [];
  1213 + foreach ($itemArr as $k => $v) {
  1214 + $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  1215 + }
  1216 + return implode(",\n", $resultArr);
  1217 + } else {
  1218 + return '';
  1219 + }
  1220 + }
  1221 +
  1222 + /**
  1223 + * 读取数据和语言数组列表
  1224 + * @param array $arr
  1225 + * @param boolean $withTpl
  1226 + * @return array
  1227 + */
  1228 + protected function getLangArray($arr, $withTpl = true)
  1229 + {
  1230 + $langArr = [];
  1231 + foreach ($arr as $k => $v) {
  1232 + $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  1233 + }
  1234 + return $langArr;
  1235 + }
  1236 +
  1237 + /**
  1238 + * 将数据转换成带字符串
  1239 + * @param array $arr
  1240 + * @return string
  1241 + */
  1242 + protected function getArrayString($arr)
  1243 + {
  1244 + if (!is_array($arr)) {
  1245 + return $arr;
  1246 + }
  1247 + $stringArr = [];
  1248 + foreach ($arr as $k => $v) {
  1249 + $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  1250 + if (!$is_var) {
  1251 + $v = str_replace("'", "\'", $v);
  1252 + $k = str_replace("'", "\'", $k);
  1253 + }
  1254 + $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  1255 + }
  1256 + return implode(", ", $stringArr);
  1257 + }
  1258 +
  1259 + protected function getItemArray($item, $field, $comment)
  1260 + {
  1261 + $itemArr = [];
  1262 + $comment = str_replace(',', ',', $comment);
  1263 + if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  1264 + list($fieldLang, $item) = explode(':', $comment);
  1265 + $itemArr = [];
  1266 + foreach (explode(',', $item) as $k => $v) {
  1267 + $valArr = explode('=', $v);
  1268 + if (count($valArr) == 2) {
  1269 + list($key, $value) = $valArr;
  1270 + $itemArr[$key] = $field . ' ' . $key;
  1271 + }
  1272 + }
  1273 + } else {
  1274 + foreach ($item as $k => $v) {
  1275 + $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  1276 + }
  1277 + }
  1278 + return $itemArr;
  1279 + }
  1280 +
  1281 + protected function getFieldType(& $v)
  1282 + {
  1283 + $inputType = 'text';
  1284 + switch ($v['DATA_TYPE']) {
  1285 + case 'bigint':
  1286 + case 'int':
  1287 + case 'mediumint':
  1288 + case 'smallint':
  1289 + case 'tinyint':
  1290 + $inputType = 'number';
  1291 + break;
  1292 + case 'enum':
  1293 + case 'set':
  1294 + $inputType = 'select';
  1295 + break;
  1296 + case 'decimal':
  1297 + case 'double':
  1298 + case 'float':
  1299 + $inputType = 'number';
  1300 + break;
  1301 + case 'longtext':
  1302 + case 'text':
  1303 + case 'mediumtext':
  1304 + case 'smalltext':
  1305 + case 'tinytext':
  1306 + $inputType = 'textarea';
  1307 + break;
  1308 + case 'year':
  1309 + case 'date':
  1310 + case 'time':
  1311 + case 'datetime':
  1312 + case 'timestamp':
  1313 + $inputType = 'datetime';
  1314 + break;
  1315 + default:
  1316 + break;
  1317 + }
  1318 + $fieldsName = $v['COLUMN_NAME'];
  1319 + // 指定后缀说明也是个时间字段
  1320 + if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  1321 + $inputType = 'datetime';
  1322 + }
  1323 + // 指定后缀结尾且类型为enum,说明是个单选框
  1324 + if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  1325 + $inputType = "radio";
  1326 + }
  1327 + // 指定后缀结尾且类型为set,说明是个复选框
  1328 + if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  1329 + $inputType = "checkbox";
  1330 + }
  1331 + // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1332 + if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1333 + $inputType = "switch";
  1334 + }
  1335 + // 指定后缀结尾城市选择框
  1336 + if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1337 + $inputType = "citypicker";
  1338 + }
  1339 + // 指定后缀结尾JSON配置
  1340 + if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1341 + $inputType = "fieldlist";
  1342 + }
  1343 + return $inputType;
  1344 + }
  1345 +
  1346 + /**
  1347 + * 判断是否符合指定后缀
  1348 + * @param string $field 字段名称
  1349 + * @param mixed $suffixArr 后缀
  1350 + * @return boolean
  1351 + */
  1352 + protected function isMatchSuffix($field, $suffixArr)
  1353 + {
  1354 + $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1355 + foreach ($suffixArr as $k => $v) {
  1356 + if (preg_match("/{$v}$/i", $field)) {
  1357 + return true;
  1358 + }
  1359 + }
  1360 + return false;
  1361 + }
  1362 +
  1363 + /**
  1364 + * 获取表单分组数据
  1365 + * @param string $field
  1366 + * @param string $content
  1367 + * @return string
  1368 + */
  1369 + protected function getFormGroup($field, $content)
  1370 + {
  1371 + $langField = mb_ucfirst($field);
  1372 + return <<<EOD
  1373 + <div class="form-group">
  1374 + <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1375 + <div class="col-xs-12 col-sm-8">
  1376 + {$content}
  1377 + </div>
  1378 + </div>
  1379 +EOD;
  1380 + }
  1381 +
  1382 + /**
  1383 + * 获取图片模板数据
  1384 + * @param string $field
  1385 + * @param string $content
  1386 + * @return string
  1387 + */
  1388 + protected function getImageUpload($field, $content)
  1389 + {
  1390 + $uploadfilter = $selectfilter = '';
  1391 + if ($this->isMatchSuffix($field, $this->imageField)) {
  1392 + $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1393 + $selectfilter = ' data-mimetype="image/*"';
  1394 + }
  1395 + $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1396 + $preview = ' data-preview-id="p-' . $field . '"';
  1397 + $previewcontainer = $preview ? '<ul class="row list-inline faupload-preview" id="p-' . $field . '"></ul>' : '';
  1398 + return <<<EOD
  1399 +<div class="input-group">
  1400 + {$content}
  1401 + <div class="input-group-addon no-border no-padding">
  1402 + <span><button type="button" id="faupload-{$field}" class="btn btn-danger faupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  1403 + <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>
  1404 + </div>
  1405 + <span class="msg-box n-right" for="c-{$field}"></span>
  1406 + </div>
  1407 + {$previewcontainer}
  1408 +EOD;
  1409 + }
  1410 +
  1411 + /**
  1412 + * 获取JS列数据
  1413 + * @param string $field
  1414 + * @param string $datatype
  1415 + * @param string $extend
  1416 + * @param array $itemArr
  1417 + * @return string
  1418 + */
  1419 + protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1420 + {
  1421 + $lang = mb_ucfirst($field);
  1422 + $formatter = '';
  1423 + foreach ($this->fieldFormatterSuffix as $k => $v) {
  1424 + if (preg_match("/{$k}$/i", $field)) {
  1425 + if (is_array($v)) {
  1426 + if (in_array($datatype, $v['type'])) {
  1427 + $formatter = $v['name'];
  1428 + break;
  1429 + }
  1430 + } else {
  1431 + $formatter = $v;
  1432 + break;
  1433 + }
  1434 + }
  1435 + }
  1436 + $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  1437 +
  1438 + if ($datatype == 'set') {
  1439 + $formatter = 'label';
  1440 + }
  1441 + foreach ($itemArr as $k => &$v) {
  1442 + if (substr($v, 0, 3) !== '__(') {
  1443 + $v = "__('" . mb_ucfirst($v) . "')";
  1444 + }
  1445 + }
  1446 + unset($v);
  1447 + $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
  1448 + $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1449 + if ($itemArr) {
  1450 + $html .= ", searchList: " . $searchList;
  1451 + }
  1452 +
  1453 + // 文件、图片、权重等字段默认不加入搜索栏,字符串类型默认LIKE
  1454 + $noSearchFiles = ['file$', 'files$', 'image$', 'images$', '^weigh$'];
  1455 + if(preg_match("/" . implode('|', $noSearchFiles) . "/i", $field)){
  1456 + $html .= ", operate: false";
  1457 + }else if(in_array($datatype, ['varchar'])) {
  1458 + $html .= ", operate: 'LIKE'";
  1459 + }
  1460 +
  1461 + if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1462 + $html .= ", operate:'RANGE', addclass:'datetimerange', autocomplete:false";
  1463 + } elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
  1464 + $html .= ", operate:'BETWEEN'";
  1465 + }
  1466 + if (in_array($datatype, ['set'])) {
  1467 + $html .= ", operate:'FIND_IN_SET'";
  1468 + }
  1469 + if (in_array($formatter, ['image', 'images'])) {
  1470 + $html .= ", events: Table.api.events.image";
  1471 + }
  1472 + if (in_array($formatter, ['toggle'])) {
  1473 + $html .= ", table: table";
  1474 + }
  1475 + if ($itemArr && !$formatter) {
  1476 + $formatter = 'normal';
  1477 + }
  1478 + if ($formatter) {
  1479 + $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1480 + } else {
  1481 + $html .= "}";
  1482 + }
  1483 + return $html;
  1484 + }
  1485 +
  1486 + protected function getCamelizeName($uncamelized_words, $separator = '_')
  1487 + {
  1488 + $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1489 + return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1490 + }
  1491 +
  1492 + protected function getFieldListName($field)
  1493 + {
  1494 + return $this->getCamelizeName($field) . 'List';
  1495 + }
  1496 +}
  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 + public function import()
  29 + {
  30 + parent::import();
  31 + }
  32 +
  33 + /**
  34 + * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  35 + * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  36 + * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  37 + */
  38 +
  39 +{%controllerIndex%}
  40 +}
  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 + //如果发送的来源是Selectpage,则转发到Selectpage
  13 + if ($this->request->request('keyField')) {
  14 + return $this->selectpage();
  15 + }
  16 + list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  17 +
  18 + $list = $this->model
  19 + {%relationWithList%}
  20 + ->where($where)
  21 + ->order($sort, $order)
  22 + ->paginate($limit);
  23 +
  24 + foreach ($list as $row) {
  25 + {%visibleFieldList%}
  26 + {%relationVisibleFieldList%}
  27 + }
  28 +
  29 + $result = array("total" => $list->total(), "rows" => $list->items());
  30 +
  31 + return json($result);
  32 + }
  33 + return $this->view->fetch();
  34 + }
  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 + <div class="checkbox">
  3 + {foreach name="{%fieldList%}" item="vo"}
  4 + <label for="{%fieldName%}-{$key}"><input id="{%fieldName%}-{$key}" name="{%fieldName%}" type="checkbox" value="{$key}" {in name="key" value="{%selectedValue%}"}checked{/in} /> {$vo}</label>
  5 + {/foreach}
  6 + </div>
  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="{:$Think.get.{%field%} === null ? 'active' : ''}"><a href="#t-all" data-value="" data-toggle="tab">{:__('All')}</a></li>
  6 + {foreach name="{%fieldName%}List" item="vo"}
  7 + <li class="{:$Think.get.{%field%} === (string)$key ? 'active' : ''}"><a href="#t-{$key}" data-value="{$key}" data-toggle="tab">{$vo}</a></li>
  8 + {/foreach}
  9 + </ul>
  10 + </div>
  1 +
  2 + <div class="radio">
  3 + {foreach name="{%fieldList%}" item="vo"}
  4 + <label for="{%fieldName%}-{$key}"><input id="{%fieldName%}-{$key}" name="{%fieldName%}" type="radio" value="{$key}" {in name="key" value="{%selectedValue%}"}checked{/in} /> {$vo}</label>
  5 + {/foreach}
  6 + </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 + <select {%attrStr%}>
  3 + {foreach name="{%fieldList%}" item="vo"}
  4 + <option value="{$key}" {in name="key" value="{%selectedValue%}"}selected{/in}>{$vo}</option>
  5 + {/foreach}
  6 + </select>
  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 + import_url: '{%controllerUrl%}/import',
  14 + table: '{%table%}',
  15 + }
  16 + });
  17 +
  18 + var table = $("#table");
  19 +
  20 + // 初始化表格
  21 + table.bootstrapTable({
  22 + url: $.fn.bootstrapTable.defaults.extend.index_url,
  23 + pk: '{%pk%}',
  24 + sortName: '{%order%}',
  25 + columns: [
  26 + [
  27 + {%javascriptList%}
  28 + ]
  29 + ]
  30 + });
  31 +
  32 + // 为表格绑定事件
  33 + Table.api.bindevent(table);
  34 + },{%recyclebinJs%}
  35 + add: function () {
  36 + Controller.api.bindevent();
  37 + },
  38 + edit: function () {
  39 + Controller.api.bindevent();
  40 + },
  41 + api: {
  42 + bindevent: function () {
  43 + Form.api.bindevent($("form[role=form]"));
  44 + }
  45 + }
  46 + };
  47 + return Controller;
  48 +});
  1 +<?php
  2 +
  3 +return [
  4 +{%langList%}
  5 +];
  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 + public function {%methodName%}($value, $data)
  3 + {
  4 + $value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
  5 + return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
  6 + }
  1 +
  2 + protected static function init()
  3 + {
  4 + self::afterInsert(function ($row) {
  5 + $pk = $row->getPk();
  6 + $row->getQuery()->where($pk, $row[$pk])->update(['{%order%}' => $row[$pk]]);
  7 + });
  8 + }
  1 +
  2 + public function {%relationMethod%}()
  3 + {
  4 + return $this->{%relationMode%}('{%relationClassName%}', '{%relationForeignKey%}', '{%relationPrimaryKey%}', [], 'LEFT')->setEagerlyType(0);
  5 + }
  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 + public function {%methodName%}($value, $data)
  3 + {
  4 + $value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
  5 + $list = $this->{%listMethodName%}();
  6 + return isset($list[$value]) ? $list[$value] : '';
  7 + }
  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 +
  2 + public function {%methodName%}($value, $data)
  3 + {
  4 + $value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
  5 + $list = $this->{%listMethodName%}();
  6 + return isset($list[$value]) ? $list[$value] : '';
  7 + }
  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 {%modelNamespace%};
  4 +
  5 +use think\Model;
  6 +
  7 +class {%relationName%} extends Model
  8 +{
  9 + // 表名
  10 + protected ${%relationTableType%} = '{%relationTableTypeName%}';
  11 +
  12 +}
  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 +}
  1 +<?php
  2 +
  3 +namespace app\admin\command;
  4 +
  5 +use fast\Random;
  6 +use PDO;
  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\Lang;
  15 +use think\Request;
  16 +use think\View;
  17 +
  18 +class Install extends Command
  19 +{
  20 + protected $model = null;
  21 + /**
  22 + * @var \think\View 视图类实例
  23 + */
  24 + protected $view;
  25 +
  26 + /**
  27 + * @var \think\Request Request 实例
  28 + */
  29 + protected $request;
  30 +
  31 + protected function configure()
  32 + {
  33 + $config = Config::get('database');
  34 + $this
  35 + ->setName('install')
  36 + ->addOption('hostname', 'a', Option::VALUE_OPTIONAL, 'mysql hostname', $config['hostname'])
  37 + ->addOption('hostport', 'o', Option::VALUE_OPTIONAL, 'mysql hostport', $config['hostport'])
  38 + ->addOption('database', 'd', Option::VALUE_OPTIONAL, 'mysql database', $config['database'])
  39 + ->addOption('prefix', 'r', Option::VALUE_OPTIONAL, 'table prefix', $config['prefix'])
  40 + ->addOption('username', 'u', Option::VALUE_OPTIONAL, 'mysql username', $config['username'])
  41 + ->addOption('password', 'p', Option::VALUE_OPTIONAL, 'mysql password', $config['password'])
  42 + ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', false)
  43 + ->setDescription('New installation of FastAdmin');
  44 + }
  45 +
  46 + /**
  47 + * 命令行安装
  48 + */
  49 + protected function execute(Input $input, Output $output)
  50 + {
  51 + define('INSTALL_PATH', APP_PATH . 'admin' . DS . 'command' . DS . 'Install' . DS);
  52 + // 覆盖安装
  53 + $force = $input->getOption('force');
  54 + $hostname = $input->getOption('hostname');
  55 + $hostport = $input->getOption('hostport');
  56 + $database = $input->getOption('database');
  57 + $prefix = $input->getOption('prefix');
  58 + $username = $input->getOption('username');
  59 + $password = $input->getOption('password');
  60 +
  61 + $installLockFile = INSTALL_PATH . "install.lock";
  62 + if (is_file($installLockFile) && !$force) {
  63 + throw new Exception("\nFastAdmin already installed!\nIf you need to reinstall again, use the parameter --force=true ");
  64 + }
  65 +
  66 + $adminUsername = 'admin';
  67 + $adminPassword = Random::alnum(10);
  68 + $adminEmail = 'admin@admin.com';
  69 + $siteName = __('My Website');
  70 +
  71 + $adminName = $this->installation($hostname, $hostport, $database, $username, $password, $prefix, $adminUsername, $adminPassword, $adminEmail, $siteName);
  72 + if ($adminName) {
  73 + $output->highlight("Admin url:http://www.yoursite.com/{$adminName}");
  74 + }
  75 +
  76 + $output->highlight("Admin username:{$adminUsername}");
  77 + $output->highlight("Admin password:{$adminPassword}");
  78 +
  79 + \think\Cache::rm('__menu__');
  80 +
  81 + $output->info("Install Successed!");
  82 + }
  83 +
  84 + /**
  85 + * PC端安装
  86 + */
  87 + public function index()
  88 + {
  89 + $this->view = View::instance(Config::get('template'), Config::get('view_replace_str'));
  90 + $this->request = Request::instance();
  91 +
  92 + define('INSTALL_PATH', APP_PATH . 'admin' . DS . 'command' . DS . 'Install' . DS);
  93 + $langSet = strtolower($this->request->langset());
  94 + if (!$langSet || in_array($langSet, ['zh-cn', 'zh-hans-cn'])) {
  95 + Lang::load(INSTALL_PATH . 'zh-cn.php');
  96 + }
  97 +
  98 + $installLockFile = INSTALL_PATH . "install.lock";
  99 +
  100 + if (is_file($installLockFile)) {
  101 + echo __('The system has been installed. If you need to reinstall, please remove %s first', 'install.lock');
  102 + exit;
  103 + }
  104 + $output = function ($code, $msg, $url = null, $data = null) {
  105 + return json(['code' => $code, 'msg' => $msg, 'url' => $url, 'data' => $data]);
  106 + };
  107 +
  108 + if ($this->request->isPost()) {
  109 + $mysqlHostname = $this->request->post('mysqlHostname', '127.0.0.1');
  110 + $mysqlHostport = $this->request->post('mysqlHostport', '3306');
  111 + $hostArr = explode(':', $mysqlHostname);
  112 + if (count($hostArr) > 1) {
  113 + $mysqlHostname = $hostArr[0];
  114 + $mysqlHostport = $hostArr[1];
  115 + }
  116 + $mysqlUsername = $this->request->post('mysqlUsername', 'root');
  117 + $mysqlPassword = $this->request->post('mysqlPassword', '');
  118 + $mysqlDatabase = $this->request->post('mysqlDatabase', '');
  119 + $mysqlPrefix = $this->request->post('mysqlPrefix', 'fa_');
  120 + $adminUsername = $this->request->post('adminUsername', 'admin');
  121 + $adminPassword = $this->request->post('adminPassword', '');
  122 + $adminPasswordConfirmation = $this->request->post('adminPasswordConfirmation', '');
  123 + $adminEmail = $this->request->post('adminEmail', 'admin@admin.com');
  124 + $siteName = $this->request->post('siteName', __('My Website'));
  125 +
  126 + if ($adminPassword !== $adminPasswordConfirmation) {
  127 + return $output(0, __('The two passwords you entered did not match'));
  128 + }
  129 +
  130 + $adminName = '';
  131 + try {
  132 + $adminName = $this->installation($mysqlHostname, $mysqlHostport, $mysqlDatabase, $mysqlUsername, $mysqlPassword, $mysqlPrefix, $adminUsername, $adminPassword, $adminEmail, $siteName);
  133 + } catch (\PDOException $e) {
  134 + throw new Exception($e->getMessage());
  135 + } catch (\Exception $e) {
  136 + return $output(0, $e->getMessage());
  137 + }
  138 + return $output(1, __('Install Successed'), null, ['adminName' => $adminName]);
  139 + }
  140 + $errInfo = '';
  141 + try {
  142 + $this->checkenv();
  143 + } catch (\Exception $e) {
  144 + $errInfo = $e->getMessage();
  145 + }
  146 + return $this->view->fetch(INSTALL_PATH . "install.html", ['errInfo' => $errInfo]);
  147 + }
  148 +
  149 + /**
  150 + * 执行安装
  151 + */
  152 + protected function installation($mysqlHostname, $mysqlHostport, $mysqlDatabase, $mysqlUsername, $mysqlPassword, $mysqlPrefix, $adminUsername, $adminPassword, $adminEmail = null, $siteName = null)
  153 + {
  154 + $this->checkenv();
  155 +
  156 + if ($mysqlDatabase == '') {
  157 + throw new Exception(__('Please input correct database'));
  158 + }
  159 + if (!preg_match("/^\w{3,12}$/", $adminUsername)) {
  160 + throw new Exception(__('Please input correct username'));
  161 + }
  162 + if (!preg_match("/^[\S]{6,16}$/", $adminPassword)) {
  163 + throw new Exception(__('Please input correct password'));
  164 + }
  165 + if ($siteName == '' || preg_match("/fast" . "admin/i", $siteName)) {
  166 + throw new Exception(__('Please input correct website'));
  167 + }
  168 +
  169 + $sql = file_get_contents(INSTALL_PATH . 'fastadmin.sql');
  170 +
  171 + $sql = str_replace("`fa_", "`{$mysqlPrefix}", $sql);
  172 +
  173 + // 先尝试能否自动创建数据库
  174 + $config = Config::get('database');
  175 + try {
  176 + $pdo = new PDO("{$config['type']}:host={$mysqlHostname}" . ($mysqlHostport ? ";port={$mysqlHostport}" : ''), $mysqlUsername, $mysqlPassword);
  177 + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  178 + $pdo->query("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabase}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  179 +
  180 + // 连接install命令中指定的数据库
  181 + $instance = Db::connect([
  182 + 'type' => "{$config['type']}",
  183 + 'hostname' => "{$mysqlHostname}",
  184 + 'hostport' => "{$mysqlHostport}",
  185 + 'database' => "{$mysqlDatabase}",
  186 + 'username' => "{$mysqlUsername}",
  187 + 'password' => "{$mysqlPassword}",
  188 + 'prefix' => "{$mysqlPrefix}",
  189 + ]);
  190 +
  191 + // 查询一次SQL,判断连接是否正常
  192 + $instance->execute("SELECT 1");
  193 +
  194 + // 调用原生PDO对象进行批量查询
  195 + $instance->getPdo()->exec($sql);
  196 + } catch (\PDOException $e) {
  197 + throw new Exception($e->getMessage());
  198 + }
  199 + // 后台入口文件
  200 + $adminFile = ROOT_PATH . 'public' . DS . 'admin.php';
  201 +
  202 + // 数据库配置文件
  203 + $dbConfigFile = APP_PATH . 'database.php';
  204 + $config = @file_get_contents($dbConfigFile);
  205 + $callback = function ($matches) use ($mysqlHostname, $mysqlHostport, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $mysqlPrefix) {
  206 + $field = "mysql" . ucfirst($matches[1]);
  207 + $replace = $$field;
  208 + if ($matches[1] == 'hostport' && $mysqlHostport == 3306) {
  209 + $replace = '';
  210 + }
  211 + return "'{$matches[1]}'{$matches[2]}=>{$matches[3]}Env::get('database.{$matches[1]}', '{$replace}'),";
  212 + };
  213 + $config = preg_replace_callback("/'(hostname|database|username|password|hostport|prefix)'(\s+)=>(\s+)Env::get\((.*)\)\,/", $callback, $config);
  214 +
  215 + // 检测能否成功写入数据库配置
  216 + $result = @file_put_contents($dbConfigFile, $config);
  217 + if (!$result) {
  218 + throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/database.php'));
  219 + }
  220 +
  221 + // 变更默认管理员密码
  222 + $adminPassword = $adminPassword ? $adminPassword : Random::alnum(8);
  223 + $adminEmail = $adminEmail ? $adminEmail : "admin@admin.com";
  224 + $newSalt = substr(md5(uniqid(true)), 0, 6);
  225 + $newPassword = md5(md5($adminPassword) . $newSalt);
  226 + $data = ['username' => $adminUsername, 'email' => $adminEmail, 'password' => $newPassword, 'salt' => $newSalt];
  227 + $instance->name('admin')->where('username', 'admin')->update($data);
  228 +
  229 + // 变更前台默认用户的密码,随机生成
  230 + $newSalt = substr(md5(uniqid(true)), 0, 6);
  231 + $newPassword = md5(md5(Random::alnum(8)) . $newSalt);
  232 + $instance->name('user')->where('username', 'admin')->update(['password' => $newPassword, 'salt' => $newSalt]);
  233 +
  234 + // 修改后台入口
  235 + $adminName = '';
  236 + if (is_file($adminFile)) {
  237 + $adminName = Random::alpha(10) . '.php';
  238 + rename($adminFile, ROOT_PATH . 'public' . DS . $adminName);
  239 + }
  240 +
  241 + //修改站点名称
  242 + if ($siteName != config('site.name')) {
  243 + $instance->name('config')->where('name', 'name')->update(['value' => $siteName]);
  244 + $configFile = CONF_PATH . 'extra' . DS . 'site.php';
  245 + $config = include $configFile;
  246 + $configList = $instance->name("config")->select();
  247 + foreach ($configList as $k => $value) {
  248 + if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
  249 + $value['value'] = explode(',', $value['value']);
  250 + }
  251 + if ($value['type'] == 'array') {
  252 + $value['value'] = (array)json_decode($value['value'], true);
  253 + }
  254 + $config[$value['name']] = $value['value'];
  255 + }
  256 + $config['name'] = $siteName;
  257 + file_put_contents($configFile, '<?php' . "\n\nreturn " . var_export_short($config) . ";\n");
  258 + }
  259 +
  260 + $installLockFile = INSTALL_PATH . "install.lock";
  261 + //检测能否成功写入lock文件
  262 + $result = @file_put_contents($installLockFile, 1);
  263 + if (!$result) {
  264 + throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/admin/command/Install/install.lock'));
  265 + }
  266 +
  267 + return $adminName;
  268 + }
  269 +
  270 + /**
  271 + * 检测环境
  272 + */
  273 + protected function checkenv()
  274 + {
  275 + // 检测目录是否存在
  276 + $checkDirs = [
  277 + 'thinkphp',
  278 + 'vendor',
  279 + 'public' . DS . 'assets' . DS . 'libs'
  280 + ];
  281 +
  282 + //数据库配置文件
  283 + $dbConfigFile = APP_PATH . 'database.php';
  284 +
  285 + if (version_compare(PHP_VERSION, '7.0.0', '<')) {
  286 + throw new Exception(__("The current version %s is too low, please use PHP 7.0 or higher", PHP_VERSION));
  287 + }
  288 + if (!extension_loaded("PDO")) {
  289 + throw new Exception(__("PDO is not currently installed and cannot be installed"));
  290 + }
  291 + if (!is_really_writable($dbConfigFile)) {
  292 + throw new Exception(__('The current permissions are insufficient to write the configuration file application/database.php'));
  293 + }
  294 + foreach ($checkDirs as $k => $v) {
  295 + if (!is_dir(ROOT_PATH . $v)) {
  296 + throw new Exception(__('Please go to the official website to download the full package or resource package and try to install'));
  297 + break;
  298 + }
  299 + }
  300 + return true;
  301 + }
  302 +}