作者 jinglong

新建项目

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

要显示太多修改。

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

{
"directory" : "public/assets/libs",
"ignoredDependencies": [
"file-saver",
"html2canvas",
"jspdf",
"jspdf-autotable"
]
}
\ No newline at end of file
... ...
[app]
debug = false
trace = false
[database]
hostname = 127.0.0.1
database = fastadmin
username = root
password = root
hostport = 3306
prefix = fa_
... ...
.idea/
runtime/
... ...
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "{}" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright 2017 Karson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
... ...
FastAdmin是一款基于ThinkPHP5+Bootstrap的极速后台开发框架。
## **主要特性**
* 基于`Auth`验证的权限管理系统
* 支持无限级父子级权限继承,父级的管理员可任意增删改子级管理员及权限设置
* 支持单管理员多角色
* 支持管理子级数据或个人数据
* 强大的一键生成功能
* 一键生成CRUD,包括控制器、模型、视图、JS、语言包、菜单、回收站等
* 一键压缩打包JS和CSS文件,一键CDN静态资源部署
* 一键生成控制器菜单和规则
* 一键生成API接口文档
* 完善的前端功能组件开发
* 基于`AdminLTE`二次开发
* 基于`Bootstrap`开发,自适应手机、平板、PC
* 基于`RequireJS`进行JS模块管理,按需加载
* 基于`Less`进行样式开发
* 基于`Bower`进行前端组件包管理
* 强大的插件扩展功能,在线安装卸载升级插件
* 通用的会员模块和API模块
* 共用同一账号体系的Web端会员中心权限验证和API接口会员权限验证
* 二级域名部署支持,同时域名支持绑定到插件
* 多语言支持,服务端及客户端支持
* 强大的第三方模块支持([CMS](https://www.fastadmin.net/store/cms.html)[博客](https://www.fastadmin.net/store/blog.html)[知识付费问答](https://www.fastadmin.net/store/ask.html))
* 整合第三方短信接口(阿里云、腾讯云短信)
* 无缝整合第三方云存储(七牛、阿里云OSS、又拍云)功能
* 第三方富文本编辑器支持(Summernote、Kindeditor、百度编辑器)
* 第三方登录(QQ、微信、微博)整合
* 第三方支付(微信、支付宝)无缝整合,微信支持PC端扫码支付
* 丰富的插件应用市场
## **安装使用**
https://doc.fastadmin.net
## **在线演示**
https://demo.fastadmin.net
用户名:admin
密 码:123456
提 示:演示站数据无法进行修改,请下载源码安装体验全部功能
## **界面截图**
![控制台](https://gitee.com/uploads/images/2017/0411/113717_e99ff3e7_10933.png "控制台")
## **问题反馈**
在使用中有任何问题,请使用以下联系方式联系我们
交流社区: https://forum.fastadmin.net
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群)
Email: (karsonzhang#163.com, 把#换成@)
Github: https://github.com/karsonzhang/fastadmin
Gitee: https://gitee.com/karson/fastadmin
## **特别鸣谢**
感谢以下的项目,排名不分先后
ThinkPHP:http://www.thinkphp.cn
AdminLTE:https://adminlte.io
Bootstrap:http://getbootstrap.com
jQuery:http://jquery.com
Bootstrap-table:https://github.com/wenzhixin/bootstrap-table
Nice-validator: https://validator.niceue.com
SelectPage: https://github.com/TerryZ/SelectPage
## **版权信息**
FastAdmin遵循Apache2开源协议发布,并提供免费使用。
本项目包含的第三方源码和二进制文件之版权信息另行标注。
版权所有Copyright © 2017-2019 by FastAdmin (https://www.fastadmin.net)
All rights reserved。
\ No newline at end of file
... ...
deny from all
\ No newline at end of file
... ...
<?php
namespace app\admin\behavior;
class AdminLog
{
public function run(&$params)
{
if (request()->isPost()) {
\app\admin\model\AdminLog::record();
}
}
}
... ...
<?php
namespace app\admin\command;
use think\addons\AddonException;
use think\addons\Service;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\exception\PDOException;
class Addon extends Command
{
protected function configure()
{
$this
->setName('addon')
->addOption('name', 'a', Option::VALUE_REQUIRED, 'addon name', null)
->addOption('action', 'c', Option::VALUE_REQUIRED, 'action(create/enable/disable/install/uninstall/refresh/upgrade/package/move)', 'create')
->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
->addOption('release', 'r', Option::VALUE_OPTIONAL, 'addon release version', null)
->addOption('uid', 'u', Option::VALUE_OPTIONAL, 'fastadmin uid', null)
->addOption('token', 't', Option::VALUE_OPTIONAL, 'fastadmin token', null)
->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local package', null)
->setDescription('Addon manager');
}
protected function execute(Input $input, Output $output)
{
$name = $input->getOption('name') ?: '';
$action = $input->getOption('action') ?: '';
if (stripos($name, 'addons/') !== false) {
$name = explode('/', $name)[1];
}
//强制覆盖
$force = $input->getOption('force');
//版本
$release = $input->getOption('release') ?: '';
//uid
$uid = $input->getOption('uid') ?: '';
//token
$token = $input->getOption('token') ?: '';
include dirname(__DIR__) . DS . 'common.php';
if (!$name) {
throw new Exception('Addon name could not be empty');
}
if (!$action || !in_array($action, ['create', 'disable', 'enable', 'install', 'uninstall', 'refresh', 'upgrade', 'package', 'move'])) {
throw new Exception('Please input correct action name');
}
// 查询一次SQL,判断连接是否正常
Db::execute("SELECT 1");
$addonDir = ADDON_PATH . $name . DS;
switch ($action) {
case 'create':
//非覆盖模式时如果存在则报错
if (is_dir($addonDir) && !$force) {
throw new Exception("addon already exists!\nIf you need to create again, use the parameter --force=true ");
}
//如果存在先移除
if (is_dir($addonDir)) {
rmdirs($addonDir);
}
mkdir($addonDir, 0755, true);
mkdir($addonDir . DS . 'controller', 0755, true);
$menuList = \app\common\library\Menu::export($name);
$createMenu = $this->getCreateMenu($menuList);
$prefix = Config::get('database.prefix');
$createTableSql = '';
try {
$result = Db::query("SHOW CREATE TABLE `" . $prefix . $name . "`;");
if (isset($result[0]) && isset($result[0]['Create Table'])) {
$createTableSql = $result[0]['Create Table'];
}
} catch (PDOException $e) {
}
$data = [
'name' => $name,
'addon' => $name,
'addonClassName' => ucfirst($name),
'addonInstallMenu' => $createMenu ? "\$menu = " . var_export_short($createMenu, "\t") . ";\n\tMenu::create(\$menu);" : '',
'addonUninstallMenu' => $menuList ? 'Menu::delete("' . $name . '");' : '',
'addonEnableMenu' => $menuList ? 'Menu::enable("' . $name . '");' : '',
'addonDisableMenu' => $menuList ? 'Menu::disable("' . $name . '");' : '',
];
$this->writeToFile("addon", $data, $addonDir . ucfirst($name) . '.php');
$this->writeToFile("config", $data, $addonDir . 'config.php');
$this->writeToFile("info", $data, $addonDir . 'info.ini');
$this->writeToFile("controller", $data, $addonDir . 'controller' . DS . 'Index.php');
if ($createTableSql) {
$createTableSql = str_replace("`" . $prefix, '`__PREFIX__', $createTableSql);
file_put_contents($addonDir . 'install.sql', $createTableSql);
}
$output->info("Create Successed!");
break;
case 'disable':
case 'enable':
try {
//调用启用、禁用的方法
Service::$action($name, 0);
} catch (AddonException $e) {
if ($e->getCode() != -3) {
throw new Exception($e->getMessage());
}
if (!$force) {
//如果有冲突文件则提醒
$data = $e->getData();
foreach ($data['conflictlist'] as $k => $v) {
$output->warning($v);
}
$output->info("Are you sure you want to " . ($action == 'enable' ? 'override' : 'delete') . " all those files? Type 'yes' to continue: ");
$line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
if (trim($line) != 'yes') {
throw new Exception("Operation is aborted!");
}
}
//调用启用、禁用的方法
Service::$action($name, 1);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
$output->info(ucfirst($action) . " Successed!");
break;
case 'install':
//非覆盖模式时如果存在则报错
if (is_dir($addonDir) && !$force) {
throw new Exception("addon already exists!\nIf you need to install again, use the parameter --force=true ");
}
//如果存在先移除
if (is_dir($addonDir)) {
rmdirs($addonDir);
}
// 获取本地路径
$local = $input->getOption('local');
try {
Service::install($name, 0, ['version' => $release], $local);
} catch (AddonException $e) {
if ($e->getCode() != -3) {
throw new Exception($e->getMessage());
}
if (!$force) {
//如果有冲突文件则提醒
$data = $e->getData();
foreach ($data['conflictlist'] as $k => $v) {
$output->warning($v);
}
$output->info("Are you sure you want to override all those files? Type 'yes' to continue: ");
$line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
if (trim($line) != 'yes') {
throw new Exception("Operation is aborted!");
}
}
Service::install($name, 1, ['version' => $release, 'uid' => $uid, 'token' => $token], $local);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
$output->info("Install Successed!");
break;
case 'uninstall':
//非覆盖模式时如果存在则报错
if (!$force) {
throw new Exception("If you need to uninstall addon, use the parameter --force=true ");
}
try {
Service::uninstall($name, 0);
} catch (AddonException $e) {
if ($e->getCode() != -3) {
throw new Exception($e->getMessage());
}
if (!$force) {
//如果有冲突文件则提醒
$data = $e->getData();
foreach ($data['conflictlist'] as $k => $v) {
$output->warning($v);
}
$output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
$line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
if (trim($line) != 'yes') {
throw new Exception("Operation is aborted!");
}
}
Service::uninstall($name, 1);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
$output->info("Uninstall Successed!");
break;
case 'refresh':
Service::refresh();
$output->info("Refresh Successed!");
break;
case 'upgrade':
Service::upgrade($name, ['version' => $release, 'uid' => $uid, 'token' => $token]);
$output->info("Upgrade Successed!");
break;
case 'package':
$infoFile = $addonDir . 'info.ini';
if (!is_file($infoFile)) {
throw new Exception(__('Addon info file was not found'));
}
$info = get_addon_info($name);
if (!$info) {
throw new Exception(__('Addon info file data incorrect'));
}
$infoname = isset($info['name']) ? $info['name'] : '';
if (!$infoname || !preg_match("/^[a-z]+$/i", $infoname) || $infoname != $name) {
throw new Exception(__('Addon info name incorrect'));
}
$infoversion = isset($info['version']) ? $info['version'] : '';
if (!$infoversion || !preg_match("/^\d+\.\d+\.\d+$/i", $infoversion)) {
throw new Exception(__('Addon info version incorrect'));
}
$addonTmpDir = RUNTIME_PATH . 'addons' . DS;
if (!is_dir($addonTmpDir)) {
@mkdir($addonTmpDir, 0755, true);
}
$addonFile = $addonTmpDir . $infoname . '-' . $infoversion . '.zip';
if (!class_exists('ZipArchive')) {
throw new Exception(__('ZinArchive not install'));
}
$zip = new \ZipArchive;
$zip->open($addonFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($addonDir), \RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = str_replace(DS, '/', substr($filePath, strlen($addonDir)));
if (!in_array($file->getFilename(), ['.git', '.DS_Store', 'Thumbs.db'])) {
$zip->addFile($filePath, $relativePath);
}
}
}
$zip->close();
$output->info("Package Successed!");
break;
case 'move':
$movePath = [
'adminOnlySelfDir' => ['admin/behavior', 'admin/controller', 'admin/library', 'admin/model', 'admin/validate', 'admin/view'],
'adminAllSubDir' => ['admin/lang'],
'publicDir' => ['public/assets/addons', 'public/assets/js/backend']
];
$paths = [];
$appPath = str_replace('/', DS, APP_PATH);
$rootPath = str_replace('/', DS, ROOT_PATH);
foreach ($movePath as $k => $items) {
switch ($k) {
case 'adminOnlySelfDir':
foreach ($items as $v) {
$v = str_replace('/', DS, $v);
$oldPath = $appPath . $v . DS . $name;
$newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $name;
$paths[$oldPath] = $newPath;
}
break;
case 'adminAllSubDir':
foreach ($items as $v) {
$v = str_replace('/', DS, $v);
$vPath = $appPath . $v;
$list = scandir($vPath);
foreach ($list as $_v) {
if (!in_array($_v, ['.', '..']) && is_dir($vPath . DS . $_v)) {
$oldPath = $appPath . $v . DS . $_v . DS . $name;
$newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $_v . DS . $name;
$paths[$oldPath] = $newPath;
}
}
}
break;
case 'publicDir':
foreach ($items as $v) {
$v = str_replace('/', DS, $v);
$oldPath = $rootPath . $v . DS . $name;
$newPath = $rootPath . 'addons' . DS . $name . DS . $v . DS . $name;
$paths[$oldPath] = $newPath;
}
break;
}
}
foreach ($paths as $oldPath => $newPath) {
if (is_dir($oldPath)) {
if ($force) {
if (is_dir($newPath)) {
$list = scandir($newPath);
foreach ($list as $_v) {
if (!in_array($_v, ['.', '..'])) {
$file = $newPath . DS . $_v;
@chmod($file, 0777);
@unlink($file);
}
}
@rmdir($newPath);
}
}
copydirs($oldPath, $newPath);
}
}
break;
default:
break;
}
}
/**
* 获取创建菜单的数组
* @param array $menu
* @return array
*/
protected function getCreateMenu($menu)
{
$result = [];
foreach ($menu as $k => & $v) {
$arr = [
'name' => $v['name'],
'title' => $v['title'],
];
if ($v['icon'] != 'fa fa-circle-o') {
$arr['icon'] = $v['icon'];
}
if ($v['ismenu']) {
$arr['ismenu'] = $v['ismenu'];
}
if (isset($v['childlist']) && $v['childlist']) {
$arr['sublist'] = $this->getCreateMenu($v['childlist']);
}
$result[] = $arr;
}
return $result;
}
/**
* 写入到文件
* @param string $name
* @param array $data
* @param string $pathname
* @return mixed
*/
protected function writeToFile($name, $data, $pathname)
{
$search = $replace = [];
foreach ($data as $k => $v) {
$search[] = "{%{$k}%}";
$replace[] = $v;
}
$stub = file_get_contents($this->getStub($name));
$content = str_replace($search, $replace, $stub);
if (!is_dir(dirname($pathname))) {
mkdir(strtolower(dirname($pathname)), 0755, true);
}
return file_put_contents($pathname, $content);
}
/**
* 获取基础模板
* @param string $name
* @return string
*/
protected function getStub($name)
{
return __DIR__ . '/Addon/stubs/' . $name . '.stub';
}
}
... ...
<?php
namespace addons\{%name%};
use app\common\library\Menu;
use think\Addons;
/**
* 插件
*/
class {%addonClassName%} extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
{%addonInstallMenu%}
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
{%addonUninstallMenu%}
return true;
}
/**
* 插件启用方法
* @return bool
*/
public function enable()
{
{%addonEnableMenu%}
return true;
}
/**
* 插件禁用方法
* @return bool
*/
public function disable()
{
{%addonDisableMenu%}
return true;
}
/**
* 实现钩子方法
* @return mixed
*/
public function testhook($param)
{
// 调用钩子时候的参数信息
print_r($param);
// 当前插件的配置信息,配置信息存在当前目录的config.php文件中,见下方
print_r($this->getConfig());
// 可以返回模板,模板文件默认读取的为插件目录中的文件。模板名不能为空!
//return $this->fetch('view/info');
}
}
... ...
<?php
return [
[
//配置唯一标识
'name' => 'usernmae',
//显示的标题
'title' => '用户名',
//类型
'type' => 'string',
//数据字典
'content' => [
],
//值
'value' => '',
//验证规则
'rule' => 'required',
//错误消息
'msg' => '',
//提示消息
'tip' => '',
//成功消息
'ok' => '',
//扩展信息
'extend' => ''
],
[
'name' => 'password',
'title' => '密码',
'type' => 'string',
'content' => [
],
'value' => '',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => ''
],
];
... ...
<?php
namespace addons\{%addon%}\controller;
use think\addons\Controller;
class Index extends Controller
{
public function index()
{
$this->error("当前插件暂无前台页面");
}
}
... ...
name = {%name%}
title = 插件名称{%name%}
intro = FastAdmin插件
author = yourname
website = https://www.fastadmin.net
version = 1.0.0
state = 1
\ No newline at end of file
... ...
<?php
namespace app\admin\command;
use app\admin\command\Api\library\Builder;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
class Api extends Command
{
protected function configure()
{
$site = Config::get('site');
$this
->setName('api')
->addOption('url', 'u', Option::VALUE_OPTIONAL, 'default api url', '')
->addOption('module', 'm', Option::VALUE_OPTIONAL, 'module name(admin/index/api)', 'api')
->addOption('output', 'o', Option::VALUE_OPTIONAL, 'output index file name', 'api.html')
->addOption('template', 'e', Option::VALUE_OPTIONAL, '', 'index.html')
->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override general file', false)
->addOption('title', 't', Option::VALUE_OPTIONAL, 'document title', $site['name'])
->addOption('author', 'a', Option::VALUE_OPTIONAL, 'document author', $site['name'])
->addOption('class', 'c', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'extend class', null)
->addOption('language', 'l', Option::VALUE_OPTIONAL, 'language', 'zh-cn')
->setDescription('Build Api document from controller');
}
protected function execute(Input $input, Output $output)
{
$apiDir = __DIR__ . DS . 'Api' . DS;
$force = $input->getOption('force');
$url = $input->getOption('url');
$language = $input->getOption('language');
$language = $language ? $language : 'zh-cn';
$langFile = $apiDir . 'lang' . DS . $language . '.php';
if (!is_file($langFile)) {
throw new Exception('language file not found');
}
$lang = include_once $langFile;
// 目标目录
$output_dir = ROOT_PATH . 'public' . DS;
$output_file = $output_dir . $input->getOption('output');
if (is_file($output_file) && !$force) {
throw new Exception("api index file already exists!\nIf you need to rebuild again, use the parameter --force=true ");
}
// 模板文件
$template_dir = $apiDir . 'template' . DS;
$template_file = $template_dir . $input->getOption('template');
if (!is_file($template_file)) {
throw new Exception('template file not found');
}
// 额外的类
$classes = $input->getOption('class');
// 标题
$title = $input->getOption('title');
// 作者
$author = $input->getOption('author');
// 模块
$module = $input->getOption('module');
$moduleDir = APP_PATH . $module . DS;
if (!is_dir($moduleDir)) {
throw new Exception('module not found');
}
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
if (extension_loaded('Zend OPcache')) {
$configuration = opcache_get_configuration();
$directives = $configuration['directives'];
$configName = request()->isCli() ? 'opcache.enable_cli' : 'opcache.enable';
if (!$directives[$configName]) {
throw new Exception("Please make sure {$configName} is turned on, Get help:https://forum.fastadmin.net/d/1321");
}
} else {
throw new Exception("Please make sure opcache already enabled, Get help:https://forum.fastadmin.net/d/1321");
}
}
$controllerDir = $moduleDir . Config::get('url_controller_layer') . DS;
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($controllerDir),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir() && $file->getExtension() == 'php') {
$filePath = $file->getRealPath();
$classes[] = $this->get_class_from_file($filePath);
}
}
$classes = array_unique(array_filter($classes));
$config = [
'title' => $title,
'author' => $author,
'description' => '',
'apiurl' => $url,
'language' => $language,
];
$builder = new Builder($classes);
$content = $builder->render($template_file, ['config' => $config, 'lang' => $lang]);
if (!file_put_contents($output_file, $content)) {
throw new Exception('Cannot save the content to ' . $output_file);
}
$output->info("Build Successed!");
}
/**
* get full qualified class name
*
* @param string $path_to_file
* @author JBYRNE http://jarretbyrne.com/2015/06/197/
* @return string
*/
protected function get_class_from_file($path_to_file)
{
//Grab the contents of the file
$contents = file_get_contents($path_to_file);
//Start with a blank namespace and class
$namespace = $class = "";
//Set helper values to know that we have found the namespace/class token and need to collect the string values after them
$getting_namespace = $getting_class = false;
//Go through each token and evaluate it as necessary
foreach (token_get_all($contents) as $token) {
//If this token is the namespace declaring, then flag that the next tokens will be the namespace name
if (is_array($token) && $token[0] == T_NAMESPACE) {
$getting_namespace = true;
}
//If this token is the class declaring, then flag that the next tokens will be the class name
if (is_array($token) && $token[0] == T_CLASS) {
$getting_class = true;
}
//While we're grabbing the namespace name...
if ($getting_namespace === true) {
//If the token is a string or the namespace separator...
if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) {
//Append the token's value to the name of the namespace
$namespace .= $token[1];
} elseif ($token === ';') {
//If the token is the semicolon, then we're done with the namespace declaration
$getting_namespace = false;
}
}
//While we're grabbing the class name...
if ($getting_class === true) {
//If the token is a string, it's the name of the class
if (is_array($token) && $token[0] == T_STRING) {
//Store the token's value as the class name
$class = $token[1];
//Got what we need, stope here
break;
}
}
}
//Build the fully-qualified class name and return it
return $namespace ? $namespace . '\\' . $class : $class;
}
}
... ...
<?php
return [
'Info' => '基础信息',
'Sandbox' => '在线测试',
'Sampleoutput' => '返回示例',
'Headers' => 'Headers',
'Parameters' => '参数',
'Body' => '正文',
'Name' => '名称',
'Type' => '类型',
'Required' => '必选',
'Description' => '描述',
'Send' => '提交',
'Reset' => '重置',
'Tokentips' => 'Token在会员注册或登录后都会返回,WEB端同时存在于Cookie中',
'Apiurltips' => 'API接口URL',
'Savetips' => '点击保存后Token和Api url都将保存在本地Localstorage中',
'ReturnHeaders' => '响应头',
'ReturnParameters' => '返回参数',
'Response' => '响应输出',
];
... ...
<?php
namespace app\admin\command\Api\library;
use think\Config;
/**
* @website https://github.com/calinrada/php-apidoc
* @author Calin Rada <rada.calin@gmail.com>
* @author Karson <karsonzhang@163.com>
*/
class Builder
{
/**
*
* @var \think\View
*/
public $view = null;
/**
* parse classes
* @var array
*/
protected $classes = [];
/**
*
* @param array $classes
*/
public function __construct($classes = [])
{
$this->classes = array_merge($this->classes, $classes);
$this->view = new \think\View(Config::get('template'), Config::get('view_replace_str'));
}
protected function extractAnnotations()
{
foreach ($this->classes as $class) {
$classAnnotation = Extractor::getClassAnnotations($class);
// 如果忽略
if (isset($classAnnotation['ApiInternal'])) {
continue;
}
Extractor::getClassMethodAnnotations($class);
}
$allClassAnnotation = Extractor::getAllClassAnnotations();
$allClassMethodAnnotation = Extractor::getAllClassMethodAnnotations();
// foreach ($allClassMethodAnnotation as $className => &$methods) {
// foreach ($methods as &$method) {
// //权重判断
// if ($method && !isset($method['ApiWeigh']) && isset($allClassAnnotation[$className]['ApiWeigh'])) {
// $method['ApiWeigh'] = $allClassAnnotation[$className]['ApiWeigh'];
// }
// }
// }
// unset($methods);
return [$allClassAnnotation, $allClassMethodAnnotation];
}
protected function generateHeadersTemplate($docs)
{
if (!isset($docs['ApiHeaders'])) {
return [];
}
$headerslist = array();
foreach ($docs['ApiHeaders'] as $params) {
$tr = array(
'name' => $params['name'],
'type' => $params['type'],
'sample' => isset($params['sample']) ? $params['sample'] : '',
'required' => isset($params['required']) ? $params['required'] : false,
'description' => isset($params['description']) ? $params['description'] : '',
);
$headerslist[] = $tr;
}
return $headerslist;
}
protected function generateParamsTemplate($docs)
{
if (!isset($docs['ApiParams'])) {
return [];
}
$paramslist = array();
foreach ($docs['ApiParams'] as $params) {
$tr = array(
'name' => $params['name'],
'type' => isset($params['type']) ? $params['type'] : 'string',
'sample' => isset($params['sample']) ? $params['sample'] : '',
'required' => isset($params['required']) ? $params['required'] : true,
'description' => isset($params['description']) ? $params['description'] : '',
);
$paramslist[] = $tr;
}
return $paramslist;
}
protected function generateReturnHeadersTemplate($docs)
{
if (!isset($docs['ApiReturnHeaders'])) {
return [];
}
$headerslist = array();
foreach ($docs['ApiReturnHeaders'] as $params) {
$tr = array(
'name' => $params['name'],
'type' => 'string',
'sample' => isset($params['sample']) ? $params['sample'] : '',
'required' => isset($params['required']) && $params['required'] ? 'Yes' : 'No',
'description' => isset($params['description']) ? $params['description'] : '',
);
$headerslist[] = $tr;
}
return $headerslist;
}
protected function generateReturnParamsTemplate($st_params)
{
if (!isset($st_params['ApiReturnParams'])) {
return [];
}
$paramslist = array();
foreach ($st_params['ApiReturnParams'] as $params) {
$tr = array(
'name' => $params['name'],
'type' => isset($params['type']) ? $params['type'] : 'string',
'sample' => isset($params['sample']) ? $params['sample'] : '',
'description' => isset($params['description']) ? $params['description'] : '',
);
$paramslist[] = $tr;
}
return $paramslist;
}
protected function generateBadgeForMethod($data)
{
$method = strtoupper(is_array($data['ApiMethod'][0]) ? $data['ApiMethod'][0]['data'] : $data['ApiMethod'][0]);
$labes = array(
'POST' => 'label-primary',
'GET' => 'label-success',
'PUT' => 'label-warning',
'DELETE' => 'label-danger',
'PATCH' => 'label-default',
'OPTIONS' => 'label-info'
);
return isset($labes[$method]) ? $labes[$method] : $labes['GET'];
}
public function parse()
{
list($allClassAnnotations, $allClassMethodAnnotations) = $this->extractAnnotations();
$sectorArr = [];
foreach ($allClassAnnotations as $index => $allClassAnnotation) {
$sector = isset($allClassAnnotation['ApiSector']) ? $allClassAnnotation['ApiSector'][0] : $allClassAnnotation['ApiTitle'][0];
$sectorArr[$sector] = isset($allClassAnnotation['ApiWeigh']) ? $allClassAnnotation['ApiWeigh'][0] : 0;
}
arsort($sectorArr);
$routes = include_once CONF_PATH . 'route.php';
$subdomain = false;
if (config('url_domain_deploy') && isset($routes['__domain__']) && isset($routes['__domain__']['api']) && $routes['__domain__']['api']) {
$subdomain = true;
}
$counter = 0;
$section = null;
$weigh = 0;
$docslist = [];
foreach ($allClassMethodAnnotations as $class => $methods) {
foreach ($methods as $name => $docs) {
if (isset($docs['ApiSector'][0])) {
$section = is_array($docs['ApiSector'][0]) ? $docs['ApiSector'][0]['data'] : $docs['ApiSector'][0];
} else {
$section = $class;
}
if (0 === count($docs)) {
continue;
}
$route = is_array($docs['ApiRoute'][0]) ? $docs['ApiRoute'][0]['data'] : $docs['ApiRoute'][0];
if ($subdomain) {
$route = substr($route, 4);
}
$docslist[$section][$name] = [
'id' => $counter,
'method' => is_array($docs['ApiMethod'][0]) ? $docs['ApiMethod'][0]['data'] : $docs['ApiMethod'][0],
'method_label' => $this->generateBadgeForMethod($docs),
'section' => $section,
'route' => $route,
'title' => is_array($docs['ApiTitle'][0]) ? $docs['ApiTitle'][0]['data'] : $docs['ApiTitle'][0],
'summary' => is_array($docs['ApiSummary'][0]) ? $docs['ApiSummary'][0]['data'] : $docs['ApiSummary'][0],
'body' => isset($docs['ApiBody'][0]) ? is_array($docs['ApiBody'][0]) ? $docs['ApiBody'][0]['data'] : $docs['ApiBody'][0] : '',
'headerslist' => $this->generateHeadersTemplate($docs),
'paramslist' => $this->generateParamsTemplate($docs),
'returnheaderslist' => $this->generateReturnHeadersTemplate($docs),
'returnparamslist' => $this->generateReturnParamsTemplate($docs),
'weigh' => is_array($docs['ApiWeigh'][0]) ? $docs['ApiWeigh'][0]['data'] : $docs['ApiWeigh'][0],
'return' => isset($docs['ApiReturn']) ? is_array($docs['ApiReturn'][0]) ? $docs['ApiReturn'][0]['data'] : $docs['ApiReturn'][0] : '',
];
$counter++;
}
}
//重建排序
foreach ($docslist as $index => &$methods) {
$methodSectorArr = [];
foreach ($methods as $name => $method) {
$methodSectorArr[$name] = isset($method['weigh']) ? $method['weigh'] : 0;
}
arsort($methodSectorArr);
$methods = array_merge(array_flip(array_keys($methodSectorArr)), $methods);
}
$docslist = array_merge(array_flip(array_keys($sectorArr)), $docslist);
return $docslist;
}
public function getView()
{
return $this->view;
}
/**
* 渲染
* @param string $template
* @param array $vars
* @return string
*/
public function render($template, $vars = [])
{
$docslist = $this->parse();
return $this->view->display(file_get_contents($template), array_merge($vars, ['docslist' => $docslist]));
}
}
... ...
<?php
namespace app\admin\command\Api\library;
use Exception;
/**
* Class imported from https://github.com/eriknyk/Annotations
* @author Erik Amaru Ortiz https://github.com/eriknyk‎
*
* @license http://opensource.org/licenses/bsd-license.php The BSD License
* @author Calin Rada <rada.calin@gmail.com>
*/
class Extractor
{
/**
* Static array to store already parsed annotations
* @var array
*/
private static $annotationCache;
private static $classAnnotationCache;
private static $classMethodAnnotationCache;
/**
* Indicates that annotations should has strict behavior, 'false' by default
* @var boolean
*/
private $strict = false;
/**
* Stores the default namespace for Objects instance, usually used on methods like getMethodAnnotationsObjects()
* @var string
*/
public $defaultNamespace = '';
/**
* Sets strict variable to true/false
* @param bool $value boolean value to indicate that annotations to has strict behavior
*/
public function setStrict($value)
{
$this->strict = (bool)$value;
}
/**
* Sets default namespace to use in object instantiation
* @param string $namespace default namespace
*/
public function setDefaultNamespace($namespace)
{
$this->defaultNamespace = $namespace;
}
/**
* Gets default namespace used in object instantiation
* @return string $namespace default namespace
*/
public function getDefaultAnnotationNamespace()
{
return $this->defaultNamespace;
}
/**
* Gets all anotations with pattern @SomeAnnotation() from a given class
*
* @param string $className class name to get annotations
* @return array self::$classAnnotationCache all annotated elements
*/
public static function getClassAnnotations($className)
{
if (!isset(self::$classAnnotationCache[$className])) {
$class = new \ReflectionClass($className);
self::$classAnnotationCache[$className] = self::parseAnnotations($class->getDocComment());
}
return self::$classAnnotationCache[$className];
}
/**
* 获取类所有方法的属性配置
* @param $className
* @return mixed
* @throws \ReflectionException
*/
public static function getClassMethodAnnotations($className)
{
$class = new \ReflectionClass($className);
foreach ($class->getMethods() as $object) {
self::$classMethodAnnotationCache[$className][$object->name] = self::getMethodAnnotations($className, $object->name);
}
return self::$classMethodAnnotationCache[$className];
}
public static function getAllClassAnnotations()
{
return self::$classAnnotationCache;
}
public static function getAllClassMethodAnnotations()
{
return self::$classMethodAnnotationCache;
}
/**
* Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class
*
* @param string $className class name
* @param string $methodName method name to get annotations
* @return array self::$annotationCache all annotated elements of a method given
*/
public static function getMethodAnnotations($className, $methodName)
{
if (!isset(self::$annotationCache[$className . '::' . $methodName])) {
try {
$method = new \ReflectionMethod($className, $methodName);
$class = new \ReflectionClass($className);
if (!$method->isPublic() || $method->isConstructor()) {
$annotations = array();
} else {
$annotations = self::consolidateAnnotations($method, $class);
}
} catch (\ReflectionException $e) {
$annotations = array();
}
self::$annotationCache[$className . '::' . $methodName] = $annotations;
}
return self::$annotationCache[$className . '::' . $methodName];
}
/**
* Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class
* and instance its abcAnnotation class
*
* @param string $className class name
* @param string $methodName method name to get annotations
* @return array self::$annotationCache all annotated objects of a method given
*/
public function getMethodAnnotationsObjects($className, $methodName)
{
$annotations = $this->getMethodAnnotations($className, $methodName);
$objects = array();
$i = 0;
foreach ($annotations as $annotationClass => $listParams) {
$annotationClass = ucfirst($annotationClass);
$class = $this->defaultNamespace . $annotationClass . 'Annotation';
// verify is the annotation class exists, depending if Annotations::strict is true
// if not, just skip the annotation instance creation.
if (!class_exists($class)) {
if ($this->strict) {
throw new Exception(sprintf('Runtime Error: Annotation Class Not Found: %s', $class));
} else {
// silent skip & continue
continue;
}
}
if (empty($objects[$annotationClass])) {
$objects[$annotationClass] = new $class();
}
foreach ($listParams as $params) {
if (is_array($params)) {
foreach ($params as $key => $value) {
$objects[$annotationClass]->set($key, $value);
}
} else {
$objects[$annotationClass]->set($i++, $params);
}
}
}
return $objects;
}
private static function consolidateAnnotations($method, $class)
{
$dockblockClass = $class->getDocComment();
$docblockMethod = $method->getDocComment();
$methodName = $method->getName();
$methodAnnotations = self::parseAnnotations($docblockMethod);
$classAnnotations = self::parseAnnotations($dockblockClass);
if (isset($methodAnnotations['ApiInternal']) || $methodName == '_initialize' || $methodName == '_empty') {
return [];
}
$properties = $class->getDefaultProperties();
$noNeedLogin = isset($properties['noNeedLogin']) ? is_array($properties['noNeedLogin']) ? $properties['noNeedLogin'] : [$properties['noNeedLogin']] : [];
$noNeedRight = isset($properties['noNeedRight']) ? is_array($properties['noNeedRight']) ? $properties['noNeedRight'] : [$properties['noNeedRight']] : [];
preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $docblockMethod), $methodArr);
preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $dockblockClass), $classArr);
if (!isset($methodAnnotations['ApiMethod'])) {
$methodAnnotations['ApiMethod'] = ['get'];
}
if (!isset($methodAnnotations['ApiWeigh'])) {
$methodAnnotations['ApiWeigh'] = [0];
}
if (!isset($methodAnnotations['ApiSummary'])) {
$methodAnnotations['ApiSummary'] = $methodAnnotations['ApiTitle'];
}
if ($methodAnnotations) {
foreach ($classAnnotations as $name => $valueClass) {
if (count($valueClass) !== 1) {
continue;
}
if ($name === 'ApiRoute') {
if (isset($methodAnnotations[$name])) {
$methodAnnotations[$name] = [rtrim($valueClass[0], '/') . $methodAnnotations[$name][0]];
} else {
$methodAnnotations[$name] = [rtrim($valueClass[0], '/') . '/' . $method->getName()];
}
}
if ($name === 'ApiSector') {
$methodAnnotations[$name] = $valueClass;
}
}
}
if (!isset($methodAnnotations['ApiRoute'])) {
$urlArr = [];
$className = $class->getName();
list($prefix, $suffix) = explode('\\' . \think\Config::get('url_controller_layer') . '\\', $className);
$prefixArr = explode('\\', $prefix);
$suffixArr = explode('\\', $suffix);
if ($prefixArr[0] == \think\Config::get('app_namespace')) {
$prefixArr[0] = '';
}
$urlArr = array_merge($urlArr, $prefixArr);
$urlArr[] = implode('.', array_map(function ($item) {
return \think\Loader::parseName($item);
}, $suffixArr));
$urlArr[] = $method->getName();
$methodAnnotations['ApiRoute'] = [implode('/', $urlArr)];
}
if (!isset($methodAnnotations['ApiSector'])) {
$methodAnnotations['ApiSector'] = isset($classAnnotations['ApiSector']) ? $classAnnotations['ApiSector'] : $classAnnotations['ApiTitle'];
}
if (!isset($methodAnnotations['ApiParams'])) {
$params = self::parseCustomAnnotations($docblockMethod, 'param');
foreach ($params as $k => $v) {
$arr = explode(' ', preg_replace("/[\s]+/", " ", $v));
$methodAnnotations['ApiParams'][] = [
'name' => isset($arr[1]) ? str_replace('$', '', $arr[1]) : '',
'nullable' => false,
'type' => isset($arr[0]) ? $arr[0] : 'string',
'description' => isset($arr[2]) ? $arr[2] : ''
];
}
}
$methodAnnotations['ApiPermissionLogin'] = [!in_array('*', $noNeedLogin) && !in_array($methodName, $noNeedLogin)];
$methodAnnotations['ApiPermissionRight'] = [!in_array('*', $noNeedRight) && !in_array($methodName, $noNeedRight)];
return $methodAnnotations;
}
/**
* Parse annotations
*
* @param string $docblock
* @param string $name
* @return array parsed annotations params
*/
private static function parseCustomAnnotations($docblock, $name = 'param')
{
$annotations = array();
$docblock = substr($docblock, 3, -2);
if (preg_match_all('/@' . $name . '(?:\s*(?:\(\s*)?(.*?)(?:\s*\))?)??\s*(?:\n|\*\/)/', $docblock, $matches)) {
foreach ($matches[1] as $k => $v) {
$annotations[] = $v;
}
}
return $annotations;
}
/**
* Parse annotations
*
* @param string $docblock
* @return array parsed annotations params
*/
private static function parseAnnotations($docblock)
{
$annotations = array();
// Strip away the docblock header and footer to ease parsing of one line annotations
$docblock = substr($docblock, 3, -2);
if (preg_match_all('/@(?<name>[A-Za-z_-]+)[\s\t]*\((?<args>(?:(?!\)).)*)\)\r?/s', $docblock, $matches)) {
$numMatches = count($matches[0]);
for ($i = 0; $i < $numMatches; ++$i) {
$name = $matches['name'][$i];
$value = '';
// annotations has arguments
if (isset($matches['args'][$i])) {
$argsParts = trim($matches['args'][$i]);
if ($name == 'ApiReturn') {
$value = $argsParts;
} elseif ($matches['args'][$i] != '') {
$argsParts = preg_replace("/\{(\w+)\}/", '#$1#', $argsParts);
$value = self::parseArgs($argsParts);
if (is_string($value)) {
$value = preg_replace("/\#(\w+)\#/", '{$1}', $argsParts);
}
}
}
$annotations[$name][] = $value;
}
}
if (stripos($docblock, '@ApiInternal') !== false) {
$annotations['ApiInternal'] = [true];
}
if (!isset($annotations['ApiTitle'])) {
preg_match_all("/\*[\s]+(.*)(\\r\\n|\\r|\\n)/U", str_replace('/**', '', $docblock), $matchArr);
$title = isset($matchArr[1]) && isset($matchArr[1][0]) ? $matchArr[1][0] : '';
$annotations['ApiTitle'] = [$title];
}
return $annotations;
}
/**
* Parse individual annotation arguments
*
* @param string $content arguments string
* @return array annotated arguments
*/
private static function parseArgs($content)
{
// Replace initial stars
$content = preg_replace('/^\s*\*/m', '', $content);
$data = array();
$len = strlen($content);
$i = 0;
$var = '';
$val = '';
$level = 1;
$prevDelimiter = '';
$nextDelimiter = '';
$nextToken = '';
$composing = false;
$type = 'plain';
$delimiter = null;
$quoted = false;
$tokens = array('"', '"', '{', '}', ',', '=');
while ($i <= $len) {
$prev_c = substr($content, $i - 1, 1);
$c = substr($content, $i++, 1);
if ($c === '"' && $prev_c !== "\\") {
$delimiter = $c;
//open delimiter
if (!$composing && empty($prevDelimiter) && empty($nextDelimiter)) {
$prevDelimiter = $nextDelimiter = $delimiter;
$val = '';
$composing = true;
$quoted = true;
} else {
// close delimiter
if ($c !== $nextDelimiter) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter,
$c
));
}
// validating syntax
if ($i < $len) {
if (',' !== substr($content, $i, 1) && '\\' !== $prev_c) {
throw new Exception(sprintf(
"Parse Error: missing comma separator near: ...%s<--",
substr($content, ($i - 10), $i)
));
}
}
$prevDelimiter = $nextDelimiter = '';
$composing = false;
$delimiter = null;
}
} elseif (!$composing && in_array($c, $tokens)) {
switch ($c) {
case '=':
$prevDelimiter = $nextDelimiter = '';
$level = 2;
$composing = false;
$type = 'assoc';
$quoted = false;
break;
case ',':
$level = 3;
// If composing flag is true yet,
// it means that the string was not enclosed, so it is parsing error.
if ($composing === true && !empty($prevDelimiter) && !empty($nextDelimiter)) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter,
$c
));
}
$prevDelimiter = $nextDelimiter = '';
break;
case '{':
$subc = '';
$subComposing = true;
while ($i <= $len) {
$c = substr($content, $i++, 1);
if (isset($delimiter) && $c === $delimiter) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly."
));
}
if ($c === '}') {
$subComposing = false;
break;
}
$subc .= $c;
}
// if the string is composing yet means that the structure of var. never was enclosed with '}'
if ($subComposing) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly. near: ...%s'",
$subc
));
}
$val = self::parseArgs($subc);
break;
}
} else {
if ($level == 1) {
$var .= $c;
} elseif ($level == 2) {
$val .= $c;
}
}
if ($level === 3 || $i === $len) {
if ($type == 'plain' && $i === $len) {
$data = self::castValue($var);
} else {
$data[trim($var)] = self::castValue($val, !$quoted);
}
$level = 1;
$var = $val = '';
$composing = false;
$quoted = false;
}
}
return $data;
}
/**
* Try determinate the original type variable of a string
*
* @param string $val string containing possibles variables that can be cast to bool or int
* @param boolean $trim indicate if the value passed should be trimmed after to try cast
* @return mixed returns the value converted to original type if was possible
*/
private static function castValue($val, $trim = false)
{
if (is_array($val)) {
foreach ($val as $key => $value) {
$val[$key] = self::castValue($value);
}
} elseif (is_string($val)) {
if ($trim) {
$val = trim($val);
}
$val = stripslashes($val);
$tmp = strtolower($val);
if ($tmp === 'false' || $tmp === 'true') {
$val = $tmp === 'true';
} elseif (is_numeric($val)) {
return $val + 0;
}
unset($tmp);
}
return $val;
}
}
... ...
<!DOCTYPE html>
<html lang="{$config.language}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="{$config.author}">
<title>{$config.title}</title>
<!-- Bootstrap Core CSS -->
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- Plugin CSS -->
<link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.staticfile.org/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
body {
padding-top: 70px; margin-bottom: 15px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
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;
font-weight: 400;
}
h2 { font-size: 1.6em; }
hr { margin-top: 10px; }
.tab-pane { padding-top: 10px; }
.mt0 { margin-top: 0px; }
.footer { font-size: 12px; color: #666; }
.label { display: inline-block; min-width: 65px; padding: 0.3em 0.6em 0.3em; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
.popover { max-width: 400px; max-height: 400px; overflow-y: auto;}
.list-group.panel > .list-group-item {
}
.list-group-item:last-child {
border-radius:0;
}
h4.panel-title a {
font-weight:normal;
font-size:14px;
}
h4.panel-title a .text-muted {
font-size:12px;
font-weight:normal;
font-family: 'Verdana';
}
#sidebar {
width: 220px;
position: fixed;
margin-left: -240px;
overflow-y:auto;
}
#sidebar > .list-group {
margin-bottom:0;
}
#sidebar > .list-group > a{
text-indent:0;
}
#sidebar .child {
border:1px solid #ddd;
border-bottom:none;
}
#sidebar .child > a {
border:0;
}
#sidebar .list-group a.current {
background:#f5f5f5;
}
@media (max-width: 1620px){
#sidebar {
margin:0;
}
#accordion {
padding-left:235px;
}
}
@media (max-width: 768px){
#sidebar {
display: none;
}
#accordion {
padding-left:0px;
}
}
.label-primary {
background-color: #248aff;
}
</style>
</head>
<body>
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://www.fastadmin.net" target="_blank">{$config.title}</a>
</div>
<div class="navbar-collapse collapse">
<form class="navbar-form navbar-right">
<div class="form-group">
Token:
</div>
<div class="form-group">
<input type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Tokentips}" placeholder="token" id="token" />
</div>
<div class="form-group">
Apiurl:
</div>
<div class="form-group">
<input id="apiUrl" type="text" class="form-control input-sm" data-toggle="tooltip" title="{$lang.Apiurltips}" placeholder="https://api.mydomain.com" value="{$config.apiurl}" />
</div>
<div class="form-group">
<button type="button" class="btn btn-success btn-sm" data-toggle="tooltip" title="{$lang.Savetips}" id="save_data">
<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
</button>
</div>
</form>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<!-- menu -->
<div id="sidebar">
<div class="list-group panel">
{foreach name="docslist" id="docs"}
<a href="#{$key}" class="list-group-item" data-toggle="collapse" data-parent="#sidebar">{$key} <i class="fa fa-caret-down"></i></a>
<div class="child collapse" id="{$key}">
{foreach name="docs" id="api" }
<a href="javascript:;" data-id="{$api.id}" class="list-group-item">{$api.title}</a>
{/foreach}
</div>
{/foreach}
</div>
</div>
<div class="panel-group" id="accordion">
{foreach name="docslist" id="docs"}
<h2>{$key}</h2>
<hr>
{foreach name="docs" id="api" }
<div class="panel panel-default">
<div class="panel-heading" id="heading-{$api.id}">
<h4 class="panel-title">
<span class="label {$api.method_label}">{$api.method|strtoupper}</span>
<a data-toggle="collapse" data-parent="#accordion{$api.id}" href="#collapseOne{$api.id}"> {$api.title} <span class="text-muted">{$api.route}</span></a>
</h4>
</div>
<div id="collapseOne{$api.id}" class="panel-collapse collapse">
<div class="panel-body">
<!-- Nav tabs -->
<ul class="nav nav-tabs" id="doctab{$api.id}">
<li class="active"><a href="#info{$api.id}" data-toggle="tab">{$lang.Info}</a></li>
<li><a href="#sandbox{$api.id}" data-toggle="tab">{$lang.Sandbox}</a></li>
<li><a href="#sample{$api.id}" data-toggle="tab">{$lang.Sampleoutput}</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="info{$api.id}">
<div class="well">
{$api.summary}
</div>
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Headers}</strong></div>
<div class="panel-body">
{if $api.headerslist}
<table class="table table-hover">
<thead>
<tr>
<th>{$lang.Name}</th>
<th>{$lang.Type}</th>
<th>{$lang.Required}</th>
<th>{$lang.Description}</th>
</tr>
</thead>
<tbody>
{foreach name="api['headerslist']" id="header"}
<tr>
<td>{$header.name}</td>
<td>{$header.type}</td>
<td>{$header.required?'是':'否'}</td>
<td>{$header.description}</td>
</tr>
{/foreach}
</tbody>
</table>
{else /}
{/if}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Parameters}</strong></div>
<div class="panel-body">
{if $api.paramslist}
<table class="table table-hover">
<thead>
<tr>
<th>{$lang.Name}</th>
<th>{$lang.Type}</th>
<th>{$lang.Required}</th>
<th>{$lang.Description}</th>
</tr>
</thead>
<tbody>
{foreach name="api['paramslist']" id="param"}
<tr>
<td>{$param.name}</td>
<td>{$param.type}</td>
<td>{:$param.required?'是':'否'}</td>
<td>{$param.description}</td>
</tr>
{/foreach}
</tbody>
</table>
{else /}
{/if}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Body}</strong></div>
<div class="panel-body">
{$api.body|default='无'}
</div>
</div>
</div><!-- #info -->
<div class="tab-pane" id="sandbox{$api.id}">
<div class="row">
<div class="col-md-12">
{if $api.headerslist}
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Headers}</strong></div>
<div class="panel-body">
<div class="headers">
{foreach name="api['headerslist']" id="param"}
<div class="form-group">
<label class="control-label" for="{$param.name}">{$param.name}</label>
<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}">
</div>
{/foreach}
</div>
</div>
</div>
{/if}
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Parameters}</strong></div>
<div class="panel-body">
<form enctype="application/x-www-form-urlencoded" role="form" action="{$api.route}" method="{$api.method}" name="form{$api.id}" id="form{$api.id}">
{if $api.paramslist}
{foreach name="api['paramslist']" id="param"}
<div class="form-group">
<label class="control-label" for="{$param.name}">{$param.name}</label>
<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}">
</div>
{/foreach}
{else /}
<div class="form-group">
</div>
{/if}
<div class="form-group">
<button type="submit" class="btn btn-success send" rel="{$api.id}">{$lang.Send}</button>
<button type="reset" class="btn btn-info" rel="{$api.id}">{$lang.Reset}</button>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.Response}</strong></div>
<div class="panel-body">
<div class="row">
<div class="col-md-12" style="overflow-x:auto">
<pre id="response_headers{$api.id}"></pre>
<pre id="response{$api.id}"></pre>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><strong>{$lang.ReturnParameters}</strong></div>
<div class="panel-body">
{if $api.returnparamslist}
<table class="table table-hover">
<thead>
<tr>
<th>{$lang.Name}</th>
<th>{$lang.Type}</th>
<th>{$lang.Description}</th>
</tr>
</thead>
<tbody>
{foreach name="api['returnparamslist']" id="param"}
<tr>
<td>{$param.name}</td>
<td>{$param.type}</td>
<td>{$param.description}</td>
</tr>
{/foreach}
</tbody>
</table>
{else /}
{/if}
</div>
</div>
</div>
</div>
</div><!-- #sandbox -->
<div class="tab-pane" id="sample{$api.id}">
<div class="row">
<div class="col-md-12">
<pre id="sample_response{$api.id}">{$api.return|default='无'}</pre>
</div>
</div>
</div><!-- #sample -->
</div><!-- .tab-content -->
</div>
</div>
</div>
{/foreach}
{/foreach}
</div>
<hr>
<div class="row mt0 footer">
<div class="col-md-6" align="left">
Generated on {:date('Y-m-d H:i:s')}
</div>
<div class="col-md-6" align="right">
<a href="https://www.fastadmin.net" target="_blank">FastAdmin</a>
</div>
</div>
</div> <!-- /container -->
<!-- jQuery -->
<script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
function prepareStr(str) {
try {
return syntaxHighlight(JSON.stringify(JSON.parse(str.replace(/'/g, '"')), null, 2));
} catch (e) {
return str;
}
}
var storage = (function () {
var uid = new Date;
var storage;
var result;
try {
(storage = window.localStorage).setItem(uid, uid);
result = storage.getItem(uid) == uid;
storage.removeItem(uid);
return result && storage;
} catch (exception) {
}
}());
$.fn.serializeObject = function ()
{
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (!this.value) {
return;
}
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(document).ready(function () {
if (storage) {
storage.getItem('token') && $('#token').val(storage.getItem('token'));
storage.getItem('apiUrl') && $('#apiUrl').val(storage.getItem('apiUrl'));
}
$('[data-toggle="tooltip"]').tooltip({
placement: 'bottom'
});
$(window).on("resize", function(){
$("#sidebar").css("max-height", $(window).height()-80);
});
$(window).trigger("resize");
$(document).on("click", "#sidebar .list-group > .list-group-item", function(){
$("#sidebar .list-group > .list-group-item").removeClass("current");
$(this).addClass("current");
});
$(document).on("click", "#sidebar .child a", function(){
var heading = $("#heading-"+$(this).data("id"));
if(!heading.next().hasClass("in")){
$("a", heading).trigger("click");
}
$("html,body").animate({scrollTop:heading.offset().top-70});
});
$('code[id^=response]').hide();
$.each($('pre[id^=sample_response],pre[id^=sample_post_body]'), function () {
if ($(this).html() == 'NA') {
return;
}
var str = prepareStr($(this).html());
$(this).html(str);
});
$("[data-toggle=popover]").popover({placement: 'right'});
$('[data-toggle=popover]').on('shown.bs.popover', function () {
var $sample = $(this).parent().find(".popover-content"),
str = $(this).data('content');
if (typeof str == "undefined" || str === "") {
return;
}
var str = prepareStr(str);
$sample.html('<pre>' + str + '</pre>');
});
$('body').on('click', '#save_data', function (e) {
if (storage) {
storage.setItem('token', $('#token').val());
storage.setItem('apiUrl', $('#apiUrl').val());
} else {
alert('Your browser does not support local storage');
}
});
$('body').on('click', '.send', function (e) {
e.preventDefault();
var form = $(this).closest('form');
//added /g to get all the matched params instead of only first
var matchedParamsInRoute = $(form).attr('action').match(/[^{]+(?=\})/g);
var theId = $(this).attr('rel');
//keep a copy of action attribute in order to modify the copy
//instead of the initial attribute
var url = $(form).attr('action');
var method = $(form).prop('method').toLowerCase() || 'get';
var formData = new FormData();
$(form).find('input').each(function (i, input) {
if ($(input).attr('type').toLowerCase() == 'file') {
formData.append($(input).attr('name'), $(input)[0].files[0]);
method = 'post';
} else {
formData.append($(input).attr('name'), $(input).val())
}
});
var index, key, value;
if (matchedParamsInRoute) {
var params = {};
formData.forEach(function(value, key){
params[key] = value;
});
for (index = 0; index < matchedParamsInRoute.length; ++index) {
try {
key = matchedParamsInRoute[index];
value = params[key];
if (typeof value == "undefined")
value = "";
url = url.replace("\{" + key + "\}", value);
formData.delete(key);
} catch (err) {
console.log(err);
}
}
}
var headers = {};
var token = $('#token').val();
if (token.length > 0) {
headers['token'] = token;
}
$("#sandbox" + theId + " .headers input[type=text]").each(function () {
val = $(this).val();
if (val.length > 0) {
headers[$(this).prop('name')] = val;
}
});
$.ajax({
url: $('#apiUrl').val() + url,
data: method == 'get' ? $(form).serialize() : formData,
type: method,
dataType: 'json',
contentType: false,
processData: false,
headers: headers,
xhrFields: {
withCredentials: true
},
success: function (data, textStatus, xhr) {
if (typeof data === 'object') {
var str = JSON.stringify(data, null, 2);
$('#response' + theId).html(syntaxHighlight(str));
} else {
$('#response' + theId).html(data || '');
}
$('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders());
$('#response' + theId).show();
},
error: function (xhr, textStatus, error) {
try {
var str = JSON.stringify($.parseJSON(xhr.responseText), null, 2);
} catch (e) {
var str = xhr.responseText;
}
$('#response_headers' + theId).html('HTTP ' + xhr.status + ' ' + xhr.statusText + '<br/><br/>' + xhr.getAllResponseHeaders());
$('#response' + theId).html(syntaxHighlight(str));
$('#response' + theId).show();
}
});
return false;
});
});
</script>
</body>
</html>
... ...
<?php
namespace app\admin\command;
use fast\Form;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Lang;
use think\Loader;
class Crud extends Command
{
protected $stubList = [];
protected $internalKeywords = [
'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'
];
/**
* Selectpage搜索字段关联
*/
protected $fieldSelectpageMap = [
'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids']
];
/**
* Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表
*/
protected $enumRadioSuffix = ['data', 'state', 'status'];
/**
* Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表
*/
protected $setCheckboxSuffix = ['data', 'state', 'status'];
/**
* Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
*/
protected $intDateSuffix = ['time'];
/**
* 开关后缀
*/
protected $switchSuffix = ['switch'];
/**
* 富文本后缀
*/
protected $editorSuffix = ['content'];
/**
* 城市后缀
*/
protected $citySuffix = ['city'];
/**
* JSON后缀
*/
protected $jsonSuffix = ['json'];
/**
* Selectpage对应的后缀
*/
protected $selectpageSuffix = ['_id', '_ids'];
/**
* Selectpage多选对应的后缀
*/
protected $selectpagesSuffix = ['_ids'];
/**
* 以指定字符结尾的字段格式化函数
*/
protected $fieldFormatterSuffix = [
'status' => ['type' => ['varchar', 'enum'], 'name' => 'status'],
'icon' => 'icon',
'flag' => 'flag',
'url' => 'url',
'image' => 'image',
'images' => 'images',
'avatar' => 'image',
'switch' => 'toggle',
'time' => ['type' => ['int', 'timestamp'], 'name' => 'datetime']
];
/**
* 识别为图片字段
*/
protected $imageField = ['image', 'images', 'avatar', 'avatars'];
/**
* 识别为文件字段
*/
protected $fileField = ['file', 'files'];
/**
* 保留字段
*/
protected $reservedField = ['admin_id'];
/**
* 排除字段
*/
protected $ignoreFields = [];
/**
* 排序字段
*/
protected $sortField = 'weigh';
/**
* 筛选字段
* @var string
*/
protected $headingFilterField = 'status';
/**
* 添加时间字段
* @var string
*/
protected $createTimeField = 'createtime';
/**
* 更新时间字段
* @var string
*/
protected $updateTimeField = 'updatetime';
/**
* 软删除时间字段
* @var string
*/
protected $deleteTimeField = 'deletetime';
/**
* 编辑器的Class
*/
protected $editorClass = 'editor';
/**
* langList的key最长字节数
*/
protected $fieldMaxLen = 0;
protected function configure()
{
$this
->setName('crud')
->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
->addOption('fields', 'i', Option::VALUE_OPTIONAL, 'model visible fields', null)
->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override or force delete,without tips', null)
->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
->addOption('relation', 'r', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table name without prefix', null)
->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation model name', null)
->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation foreign key', null)
->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation primary key', null)
->addOption('relationfields', 's', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table fields', null)
->addOption('relationmode', 'o', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table mode,hasone or belongsto', null)
->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null)
->addOption('setcheckboxsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate checkbox component with suffix', null)
->addOption('enumradiosuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate radio component with suffix', null)
->addOption('imagefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate image component with suffix', null)
->addOption('filefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate file component with suffix', null)
->addOption('intdatesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate date component with suffix', null)
->addOption('switchsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate switch component with suffix', null)
->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null)
->addOption('jsonsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate fieldlist component with suffix', null)
->addOption('selectpagesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate selectpage component with suffix', null)
->addOption('selectpagessuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate multiple selectpage component with suffix', null)
->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null)
->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null)
->addOption('headingfilterfield', null, Option::VALUE_OPTIONAL, 'heading filter field', null)
->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null)
->addOption('db', null, Option::VALUE_OPTIONAL, 'database config name', 'database')
->setDescription('Build CRUD controller and model from table');
}
protected function execute(Input $input, Output $output)
{
$adminPath = dirname(__DIR__) . DS;
//数据库
$db = $input->getOption('db');
//表名
$table = $input->getOption('table') ?: '';
//自定义控制器
$controller = $input->getOption('controller');
//自定义模型
$model = $input->getOption('model');
$model = $model ? $model : $controller;
//验证器类
$validate = $model;
//自定义显示字段
$fields = $input->getOption('fields');
//强制覆盖
$force = $input->getOption('force');
//是否为本地model,为0时表示为全局model将会把model放在app/common/model中
$local = $input->getOption('local');
if (!$table) {
throw new Exception('table name can\'t empty');
}
//是否生成菜单
$menu = $input->getOption("menu");
//关联表
$relation = $input->getOption('relation');
//自定义关联表模型
$relationModel = $input->getOption('relationmodel');
//模式
$relationMode = $mode = $input->getOption('relationmode');
//外键
$relationForeignKey = $input->getOption('relationforeignkey');
//主键
$relationPrimaryKey = $input->getOption('relationprimarykey');
//关联表显示字段
$relationFields = $input->getOption('relationfields');
//复选框后缀
$setcheckboxsuffix = $input->getOption('setcheckboxsuffix');
//单选框后缀
$enumradiosuffix = $input->getOption('enumradiosuffix');
//图片后缀
$imagefield = $input->getOption('imagefield');
//文件后缀
$filefield = $input->getOption('filefield');
//日期后缀
$intdatesuffix = $input->getOption('intdatesuffix');
//开关后缀
$switchsuffix = $input->getOption('switchsuffix');
//城市后缀
$citysuffix = $input->getOption('citysuffix');
//JSON配置后缀
$jsonsuffix = $input->getOption('jsonsuffix');
//selectpage后缀
$selectpagesuffix = $input->getOption('selectpagesuffix');
//selectpage多选后缀
$selectpagessuffix = $input->getOption('selectpagessuffix');
//排除字段
$ignoreFields = $input->getOption('ignorefields');
//排序字段
$sortfield = $input->getOption('sortfield');
//顶部筛选过滤字段
$headingfilterfield = $input->getOption('headingfilterfield');
//编辑器Class
$editorclass = $input->getOption('editorclass');
if ($setcheckboxsuffix) {
$this->setCheckboxSuffix = $setcheckboxsuffix;
}
if ($enumradiosuffix) {
$this->enumRadioSuffix = $enumradiosuffix;
}
if ($imagefield) {
$this->imageField = $imagefield;
}
if ($filefield) {
$this->fileField = $filefield;
}
if ($intdatesuffix) {
$this->intDateSuffix = $intdatesuffix;
}
if ($switchsuffix) {
$this->switchSuffix = $switchsuffix;
}
if ($citysuffix) {
$this->citySuffix = $citysuffix;
}
if ($jsonsuffix) {
$this->jsonSuffix = $jsonsuffix;
}
if ($selectpagesuffix) {
$this->selectpageSuffix = $selectpagesuffix;
}
if ($selectpagessuffix) {
$this->selectpagesSuffix = $selectpagessuffix;
}
if ($ignoreFields) {
$this->ignoreFields = $ignoreFields;
}
if ($editorclass) {
$this->editorClass = $editorclass;
}
if ($sortfield) {
$this->sortField = $sortfield;
}
if ($headingfilterfield) {
$this->headingFilterField = $headingfilterfield;
}
$this->reservedField = array_merge($this->reservedField, [$this->createTimeField, $this->updateTimeField, $this->deleteTimeField]);
$dbconnect = Db::connect($db);
$dbname = Config::get($db . '.database');
$prefix = Config::get($db . '.prefix');
//模块
$moduleName = 'admin';
$modelModuleName = $local ? $moduleName : 'common';
$validateModuleName = $local ? $moduleName : 'common';
//检查主表
$modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
$modelTableType = 'table';
$modelTableTypeName = $modelTableName = $modelName;
$modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
if (!$modelTableInfo) {
$modelTableType = 'name';
$modelTableName = $prefix . $modelName;
$modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
if (!$modelTableInfo) {
throw new Exception("table not found");
}
}
$modelTableInfo = $modelTableInfo[0];
$relations = [];
//检查关联表
if ($relation) {
$relationArr = $relation;
$relations = [];
foreach ($relationArr as $index => $relationTable) {
$relationName = stripos($relationTable, $prefix) === 0 ? substr($relationTable, strlen($prefix)) : $relationTable;
$relationTableType = 'table';
$relationTableTypeName = $relationTableName = $relationName;
$relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
if (!$relationTableInfo) {
$relationTableType = 'name';
$relationTableName = $prefix . $relationName;
$relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
if (!$relationTableInfo) {
throw new Exception("relation table not found");
}
}
$relationTableInfo = $relationTableInfo[0];
$relationModel = isset($relationModel[$index]) ? $relationModel[$index] : '';
list($relationNamespace, $relationName, $relationFile) = $this->getModelData($modelModuleName, $relationModel, $relationName);
$relations[] = [
//关联表基础名
'relationName' => $relationName,
//关联表类命名空间
'relationNamespace' => $relationNamespace,
//关联模型名
'relationModel' => $relationModel,
//关联文件
'relationFile' => $relationFile,
//关联表名称
'relationTableName' => $relationTableName,
//关联表信息
'relationTableInfo' => $relationTableInfo,
//关联模型表类型(name或table)
'relationTableType' => $relationTableType,
//关联模型表类型名称
'relationTableTypeName' => $relationTableTypeName,
//关联模式
'relationFields' => isset($relationFields[$index]) ? explode(',', $relationFields[$index]) : [],
//关联模式
'relationMode' => isset($relationMode[$index]) ? $relationMode[$index] : 'belongsto',
//关联表外键
'relationForeignKey' => isset($relationForeignKey[$index]) ? $relationForeignKey[$index] : Loader::parseName($relationName) . '_id',
//关联表主键
'relationPrimaryKey' => isset($relationPrimaryKey[$index]) ? $relationPrimaryKey[$index] : '',
];
}
}
//根据表名匹配对应的Fontawesome图标
$iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
$iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o';
//控制器
list($controllerNamespace, $controllerName, $controllerFile, $controllerArr) = $this->getControllerData($moduleName, $controller, $table);
//模型
list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($modelModuleName, $model, $table);
//验证器
list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($validateModuleName, $validate, $table);
//处理基础文件名,取消所有下划线并转换为小写
$baseNameArr = $controllerArr;
$baseFileName = Loader::parseName(array_pop($baseNameArr), 0);
array_push($baseNameArr, $baseFileName);
$controllerBaseName = strtolower(implode(DS, $baseNameArr));
$controllerUrl = strtolower(implode('/', $baseNameArr));
//视图文件
$viewArr = $controllerArr;
$lastValue = array_pop($viewArr);
$viewArr[] = Loader::parseName($lastValue, 0);
array_unshift($viewArr, 'view');
$viewDir = $adminPath . strtolower(implode(DS, $viewArr)) . DS;
//最终将生成的文件路径
$javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerBaseName . '.js';
$addFile = $viewDir . 'add.html';
$editFile = $viewDir . 'edit.html';
$indexFile = $viewDir . 'index.html';
$recyclebinFile = $viewDir . 'recyclebin.html';
$langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerBaseName . '.php';
//是否为删除模式
$delete = $input->getOption('delete');
if ($delete) {
$readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $recyclebinFile, $langFile, $javascriptFile];
foreach ($readyFiles as $k => $v) {
$output->warning($v);
}
if (!$force) {
$output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
$line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
if (trim($line) != 'yes') {
throw new Exception("Operation is aborted!");
}
}
foreach ($readyFiles as $k => $v) {
if (file_exists($v)) {
unlink($v);
}
//删除空文件夹
switch ($v) {
case $modelFile:
$this->removeEmptyBaseDir($v, $modelArr);
break;
case $validateFile:
$this->removeEmptyBaseDir($v, $validateArr);
break;
case $addFile:
case $editFile:
case $indexFile:
case $recyclebinFile:
$this->removeEmptyBaseDir($v, $viewArr);
break;
default:
$this->removeEmptyBaseDir($v, $controllerArr);
}
}
$output->info("Delete Successed");
return;
}
//非覆盖模式时如果存在控制器文件则报错
if (is_file($controllerFile) && !$force) {
throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
}
//非覆盖模式时如果存在模型文件则报错
if (is_file($modelFile) && !$force) {
throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
}
//非覆盖模式时如果存在验证文件则报错
if (is_file($validateFile) && !$force) {
throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
}
require $adminPath . 'common.php';
//从数据库中获取表字段信息
$sql = "SELECT * FROM `information_schema`.`columns` "
. "WHERE TABLE_SCHEMA = ? AND table_name = ? "
. "ORDER BY ORDINAL_POSITION";
//加载主表的列
$columnList = $dbconnect->query($sql, [$dbname, $modelTableName]);
$fieldArr = [];
foreach ($columnList as $k => $v) {
$fieldArr[] = $v['COLUMN_NAME'];
}
// 加载关联表的列
foreach ($relations as $index => &$relation) {
$relationColumnList = $dbconnect->query($sql, [$dbname, $relation['relationTableName']]);
$relationFieldList = [];
foreach ($relationColumnList as $k => $v) {
$relationFieldList[] = $v['COLUMN_NAME'];
}
if (!$relation['relationPrimaryKey']) {
foreach ($relationColumnList as $k => $v) {
if ($v['COLUMN_KEY'] == 'PRI') {
$relation['relationPrimaryKey'] = $v['COLUMN_NAME'];
break;
}
}
}
// 如果主键为空
if (!$relation['relationPrimaryKey']) {
throw new Exception('Relation Primary key not found!');
}
// 如果主键不在表字段中
if (!in_array($relation['relationPrimaryKey'], $relationFieldList)) {
throw new Exception('Relation Primary key not found in table!');
}
$relation['relationColumnList'] = $relationColumnList;
$relation['relationFieldList'] = $relationFieldList;
}
unset($relation);
$addList = [];
$editList = [];
$javascriptList = [];
$langList = [];
$field = 'id';
$order = 'id';
$priDefined = false;
$priKey = '';
$relationPrimaryKey = '';
foreach ($columnList as $k => $v) {
if ($v['COLUMN_KEY'] == 'PRI') {
$priKey = $v['COLUMN_NAME'];
break;
}
}
if (!$priKey) {
throw new Exception('Primary key not found!');
}
$order = $priKey;
//如果是关联模型
foreach ($relations as $index => &$relation) {
if ($relation['relationMode'] == 'hasone') {
$relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id";
$relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
if (!in_array($relationForeignKey, $relation['relationFieldList'])) {
throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']');
}
if (!in_array($relationPrimaryKey, $fieldArr)) {
throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']');
}
} else {
$relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id";
$relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey'];
if (!in_array($relationForeignKey, $fieldArr)) {
throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']');
}
if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) {
throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']');
}
}
$relation['relationForeignKey'] = $relationForeignKey;
$relation['relationPrimaryKey'] = $relationPrimaryKey;
$relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName'];
}
unset($relation);
try {
Form::setEscapeHtml(false);
$setAttrArr = [];
$getAttrArr = [];
$getEnumArr = [];
$appendAttrList = [];
$controllerAssignList = [];
$headingHtml = '{:build_heading()}';
$recyclebinHtml = '';
//循环所有字段,开始构造视图的HTML和JS信息
foreach ($columnList as $k => $v) {
$field = $v['COLUMN_NAME'];
$itemArr = [];
// 这里构建Enum和Set类型的列表数据
if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
if ($v['DATA_TYPE'] !== 'tinyint') {
$itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
$itemArr = explode(',', str_replace("'", '', $itemArr));
}
$itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
//如果类型为tinyint且有使用备注数据
if ($itemArr && $v['DATA_TYPE'] == 'tinyint') {
$v['DATA_TYPE'] = 'enum';
}
}
// 语言列表
if ($v['COLUMN_COMMENT'] != '') {
$langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
}
$inputType = '';
//保留字段不能修改和添加
if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) {
$inputType = $this->getFieldType($v);
// 如果是number类型时增加一个步长
$step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
$attrArr = ['id' => "c-{$field}"];
$cssClassArr = ['form-control'];
$fieldName = "row[{$field}]";
$defaultValue = $v['COLUMN_DEFAULT'];
$editValue = "{\$row.{$field}|htmlentities}";
// 如果默认值非null,则是一个必选项
if ($v['IS_NULLABLE'] == 'NO') {
$attrArr['data-rule'] = 'required';
}
if ($inputType == 'select') {
$cssClassArr[] = 'selectpicker';
$attrArr['class'] = implode(' ', $cssClassArr);
if ($v['DATA_TYPE'] == 'set') {
$attrArr['multiple'] = '';
$fieldName .= "[]";
}
$attrArr['name'] = $fieldName;
$this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
$itemArr = $this->getLangArray($itemArr, false);
//添加一个获取器
$this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
if ($v['DATA_TYPE'] == 'set') {
$this->setAttr($setAttrArr, $field, $inputType);
}
$this->appendAttr($appendAttrList, $field);
$formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
$formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
} elseif ($inputType == 'datetime') {
$cssClassArr[] = 'datetimepicker';
$attrArr['class'] = implode(' ', $cssClassArr);
$format = "YYYY-MM-DD HH:mm:ss";
$phpFormat = "Y-m-d H:i:s";
$fieldFunc = '';
switch ($v['DATA_TYPE']) {
case 'year':
$format = "YYYY";
$phpFormat = 'Y';
break;
case 'date':
$format = "YYYY-MM-DD";
$phpFormat = 'Y-m-d';
break;
case 'time':
$format = "HH:mm:ss";
$phpFormat = 'H:i:s';
break;
case 'timestamp':
$fieldFunc = 'datetime';
// no break
case 'datetime':
$format = "YYYY-MM-DD HH:mm:ss";
$phpFormat = 'Y-m-d H:i:s';
break;
default:
$fieldFunc = 'datetime';
$this->getAttr($getAttrArr, $field, $inputType);
$this->setAttr($setAttrArr, $field, $inputType);
$this->appendAttr($appendAttrList, $field);
break;
}
$defaultDateTime = "{:date('{$phpFormat}')}";
$attrArr['data-date-format'] = $format;
$attrArr['data-use-current'] = "true";
$formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
$formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr);
} elseif ($inputType == 'checkbox' || $inputType == 'radio') {
unset($attrArr['data-rule']);
$fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
$attrArr['name'] = "row[{$fieldName}]";
$this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
$itemArr = $this->getLangArray($itemArr, false);
//添加一个获取器
$this->getAttr($getAttrArr, $field, $inputType);
if ($inputType == 'checkbox') {
$this->setAttr($setAttrArr, $field, $inputType);
}
$this->appendAttr($appendAttrList, $field);
$defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
$formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
$formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
} elseif ($inputType == 'textarea') {
$cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : '';
$attrArr['class'] = implode(' ', $cssClassArr);
$attrArr['rows'] = 5;
$formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
$formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
} elseif ($inputType == 'switch') {
unset($attrArr['data-rule']);
if ($defaultValue === '1' || $defaultValue === 'Y') {
$yes = $defaultValue;
$no = $defaultValue === '1' ? '0' : 'N';
} else {
$no = $defaultValue;
$yes = $defaultValue === '0' ? '1' : 'Y';
}
if (!$itemArr) {
$itemArr = [$yes => 'Yes', $no => 'No'];
}
$stateNoClass = 'fa-flip-horizontal text-gray';
$formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
$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}"]);
} elseif ($inputType == 'citypicker') {
$attrArr['class'] = implode(' ', $cssClassArr);
$attrArr['data-toggle'] = "city-picker";
$formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
$formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
} elseif ($inputType == 'fieldlist') {
$itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
$itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key';
$itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value';
$formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $defaultValue]);
$formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'fieldValue' => $editValue]);
} else {
$search = $replace = '';
//特殊字段为关联搜索
if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
$inputType = 'text';
$defaultValue = '';
$attrArr['data-rule'] = 'required';
$cssClassArr[] = 'selectpage';
$selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
$attrArr['data-source'] = $selectpageController . "/index";
//如果是类型表需要特殊处理下
if ($selectpageController == 'category') {
$attrArr['data-source'] = 'category/selectpage';
$attrArr['data-params'] = '##replacetext##';
$search = '"##replacetext##"';
$replace = '\'{"custom[type]":"' . $table . '"}\'';
} elseif ($selectpageController == 'admin') {
$attrArr['data-source'] = 'auth/admin/selectpage';
} elseif ($selectpageController == 'user') {
$attrArr['data-source'] = 'user/user/index';
}
if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
$attrArr['data-multiple'] = 'true';
}
foreach ($this->fieldSelectpageMap as $m => $n) {
if (in_array($field, $n)) {
$attrArr['data-field'] = $m;
break;
}
}
}
//因为有自动完成可输入其它内容
$step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
$attrArr['class'] = implode(' ', $cssClassArr);
$isUpload = false;
if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
$isUpload = true;
}
//如果是步长则加上步长
if ($step) {
$attrArr['step'] = $step;
}
//如果是图片加上个size
if ($isUpload) {
$attrArr['size'] = 50;
}
$formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
$formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
if ($search && $replace) {
$formAddElement = str_replace($search, $replace, $formAddElement);
$formEditElement = str_replace($search, $replace, $formEditElement);
}
//如果是图片或文件
if ($isUpload) {
$formAddElement = $this->getImageUpload($field, $formAddElement);
$formEditElement = $this->getImageUpload($field, $formEditElement);
}
}
//构造添加和编辑HTML信息
$addList[] = $this->getFormGroup($field, $formAddElement);
$editList[] = $this->getFormGroup($field, $formEditElement);
}
//过滤text类型字段
if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
//主键
if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
$priDefined = true;
$javascriptList[] = "{checkbox: true}";
}
if ($this->deleteTimeField == $field) {
$recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
continue;
}
if (!$fields || in_array($field, explode(',', $fields))) {
//构造JS列信息
$javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
}
if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
$headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
}
//排序方式,如果有指定排序字段,否则按主键排序
$order = $field == $this->sortField ? $this->sortField : $order;
}
}
//循环关联表,追加语言包和JS列
foreach ($relations as $index => $relation) {
foreach ($relation['relationColumnList'] as $k => $v) {
// 不显示的字段直接过滤掉
if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
continue;
}
$relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
// 语言列表
if ($v['COLUMN_COMMENT'] != '') {
$langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
}
//过滤text类型字段
if ($v['DATA_TYPE'] != 'text') {
//构造JS列信息
$javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
}
}
}
//JS最后一列加上操作列
$javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
$addList = implode("\n", array_filter($addList));
$editList = implode("\n", array_filter($editList));
$javascriptList = implode(",\n", array_filter($javascriptList));
$langList = implode(",\n", array_filter($langList));
//数组等号对齐
$langList = array_filter(explode(",\n", $langList . ",\n"));
foreach ($langList as &$line) {
if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
$line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
}
}
unset($line);
$langList = implode(",\n", array_filter($langList));
//表注释
$tableComment = $modelTableInfo['Comment'];
$tableComment = mb_substr($tableComment, -1) == '' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
$modelInit = '';
if ($priKey != $order) {
$modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
}
$data = [
'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';",
'controllerNamespace' => $controllerNamespace,
'modelNamespace' => $modelNamespace,
'validateNamespace' => $validateNamespace,
'controllerUrl' => $controllerUrl,
'controllerName' => $controllerName,
'controllerAssignList' => implode("\n", $controllerAssignList),
'modelName' => $modelName,
'modelTableName' => $modelTableName,
'modelTableType' => $modelTableType,
'modelTableTypeName' => $modelTableTypeName,
'validateName' => $validateName,
'tableComment' => $tableComment,
'iconName' => $iconName,
'pk' => $priKey,
'order' => $order,
'table' => $table,
'tableName' => $modelTableName,
'addList' => $addList,
'editList' => $editList,
'javascriptList' => $javascriptList,
'langList' => $langList,
'sofeDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false',
'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
'relationSearch' => $relations ? 'true' : 'false',
'relationWithList' => '',
'relationMethodList' => '',
'controllerIndex' => '',
'recyclebinJs' => '',
'headingHtml' => $headingHtml,
'recyclebinHtml' => $recyclebinHtml,
'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '',
'appendAttrList' => implode(",\n", $appendAttrList),
'getEnumList' => implode("\n\n", $getEnumArr),
'getAttrList' => implode("\n\n", $getAttrArr),
'setAttrList' => implode("\n\n", $setAttrArr),
'modelInit' => $modelInit,
];
//如果使用关联模型
if ($relations) {
$relationWithList = $relationMethodList = $relationVisibleFieldList = [];
foreach ($relations as $index => $relation) {
//需要构造关联的方法
$relation['relationMethod'] = strtolower($relation['relationName']);
//关联的模式
$relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
//关联字段
$relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
//预载入的方法
$relationWithList[] = $relation['relationMethod'];
unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
//构造关联模型的方法
$relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
//如果设置了显示主表字段,则必须显式将关联表字段显示
if ($fields) {
$relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
}
//显示的字段
if ($relation['relationFields']) {
$relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
}
}
$data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
$data['relationMethodList'] = implode("\n\n", $relationMethodList);
$data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
//需要重写index方法
$data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
} elseif ($fields) {
$data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
//需要重写index方法
$data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
}
// 生成控制器文件
$this->writeToFile('controller', $data, $controllerFile);
// 生成模型文件
$this->writeToFile('model', $data, $modelFile);
if ($relations) {
foreach ($relations as $i => $relation) {
$relation['modelNamespace'] = $data['modelNamespace'];
if (!is_file($relation['relationFile'])) {
// 生成关联模型文件
$this->writeToFile('relationmodel', $relation, $relation['relationFile']);
}
}
}
// 生成验证文件
$this->writeToFile('validate', $data, $validateFile);
// 生成视图文件
$this->writeToFile('add', $data, $addFile);
$this->writeToFile('edit', $data, $editFile);
$this->writeToFile('index', $data, $indexFile);
if ($recyclebinHtml) {
$this->writeToFile('recyclebin', $data, $recyclebinFile);
$recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
$recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
$data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
}
// 生成JS文件
$this->writeToFile('javascript', $data, $javascriptFile);
// 生成语言文件
$this->writeToFile('lang', $data, $langFile);
} catch (ErrorException $e) {
throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
}
//继续生成菜单
if ($menu) {
exec("php think menu -c {$controllerUrl}");
}
$output->info("Build Successed");
}
protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
{
if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
return;
}
$fieldList = $this->getFieldListName($field);
$methodName = 'get' . ucfirst($fieldList);
foreach ($itemArr as $k => &$v) {
$v = "__('" . mb_ucfirst($v) . "')";
}
unset($v);
$itemString = $this->getArrayString($itemArr);
$getEnum[] = <<<EOD
public function {$methodName}()
{
return [{$itemString}];
}
EOD;
$controllerAssignList[] = <<<EOD
\$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
EOD;
}
protected function getAttr(&$getAttr, $field, $inputType = '')
{
if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
return;
}
$attrField = ucfirst($this->getCamelizeName($field));
$getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
}
protected function setAttr(&$setAttr, $field, $inputType = '')
{
if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
return;
}
$attrField = ucfirst($this->getCamelizeName($field));
if ($inputType == 'datetime') {
$return = <<<EOD
return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
EOD;
} elseif (in_array($inputType, ['checkbox', 'select'])) {
$return = <<<EOD
return is_array(\$value) ? implode(',', \$value) : \$value;
EOD;
}
$setAttr[] = <<<EOD
protected function set{$attrField}Attr(\$value)
{
$return
}
EOD;
}
protected function appendAttr(&$appendAttrList, $field)
{
$appendAttrList[] = <<<EOD
'{$field}_text'
EOD;
}
/**
* 移除相对的空目录
* @param $parseFile
* @param $parseArr
* @return bool
*/
protected function removeEmptyBaseDir($parseFile, $parseArr)
{
if (count($parseArr) > 1) {
$parentDir = dirname($parseFile);
for ($i = 0; $i < count($parseArr); $i++) {
try {
$iterator = new \FilesystemIterator($parentDir);
$isDirEmpty = !$iterator->valid();
if ($isDirEmpty) {
rmdir($parentDir);
$parentDir = dirname($parentDir);
} else {
return true;
}
} catch (\UnexpectedValueException $e) {
return false;
}
}
}
return true;
}
/**
* 获取控制器相关信息
* @param $module
* @param $controller
* @param $table
* @return array
*/
protected function getControllerData($module, $controller, $table)
{
return $this->getParseNameData($module, $controller, $table, 'controller');
}
/**
* 获取模型相关信息
* @param $module
* @param $model
* @param $table
* @return array
*/
protected function getModelData($module, $model, $table)
{
return $this->getParseNameData($module, $model, $table, 'model');
}
/**
* 获取验证器相关信息
* @param $module
* @param $validate
* @param $table
* @return array
*/
protected function getValidateData($module, $validate, $table)
{
return $this->getParseNameData($module, $validate, $table, 'validate');
}
/**
* 获取已解析相关信息
* @param string $module 模块名称
* @param string $name 自定义名称
* @param string $table 数据表名
* @param string $type 解析类型,本例中为controller、model、validate
* @return array
*/
protected function getParseNameData($module, $name, $table, $type)
{
$arr = [];
if (!$name) {
$parseName = Loader::parseName($table, 1);
$parseArr = [$table];
} else {
$name = str_replace(['.', '/', '\\'], '/', $name);
$arr = explode('/', $name);
$parseName = ucfirst(array_pop($arr));
$parseArr = $arr;
array_push($parseArr, $parseName);
}
//类名不能为内部关键字
if (in_array(strtolower($parseName), $this->internalKeywords)) {
throw new Exception('Unable to use internal variable:' . $parseName);
}
$appNamespace = Config::get('app_namespace');
$parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
$moduleDir = APP_PATH . $module . DS;
$parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
return [$parseNamespace, $parseName, $parseFile, $parseArr];
}
/**
* 写入到文件
* @param string $name
* @param array $data
* @param string $pathname
* @return mixed
*/
protected function writeToFile($name, $data, $pathname)
{
foreach ($data as $index => &$datum) {
$datum = is_array($datum) ? '' : $datum;
}
unset($datum);
$content = $this->getReplacedStub($name, $data);
if (!is_dir(dirname($pathname))) {
mkdir(dirname($pathname), 0755, true);
}
return file_put_contents($pathname, $content);
}
/**
* 获取替换后的数据
* @param string $name
* @param array $data
* @return string
*/
protected function getReplacedStub($name, $data)
{
foreach ($data as $index => &$datum) {
$datum = is_array($datum) ? '' : $datum;
}
unset($datum);
$search = $replace = [];
foreach ($data as $k => $v) {
$search[] = "{%{$k}%}";
$replace[] = $v;
}
$stubname = $this->getStub($name);
if (isset($this->stubList[$stubname])) {
$stub = $this->stubList[$stubname];
} else {
$this->stubList[$stubname] = $stub = file_get_contents($stubname);
}
$content = str_replace($search, $replace, $stub);
return $content;
}
/**
* 获取基础模板
* @param string $name
* @return string
*/
protected function getStub($name)
{
return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
}
protected function getLangItem($field, $content)
{
if ($content || !Lang::has($field)) {
$this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
$content = str_replace(',', ',', $content);
if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
list($fieldLang, $item) = explode(':', $content);
$itemArr = [$field => $fieldLang];
foreach (explode(',', $item) as $k => $v) {
$valArr = explode('=', $v);
if (count($valArr) == 2) {
list($key, $value) = $valArr;
$itemArr[$field . ' ' . $key] = $value;
$this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
}
}
} else {
$itemArr = [$field => $content];
}
$resultArr = [];
foreach ($itemArr as $k => $v) {
$resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
}
return implode(",\n", $resultArr);
} else {
return '';
}
}
/**
* 读取数据和语言数组列表
* @param array $arr
* @param boolean $withTpl
* @return array
*/
protected function getLangArray($arr, $withTpl = true)
{
$langArr = [];
foreach ($arr as $k => $v) {
$langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
}
return $langArr;
}
/**
* 将数据转换成带字符串
* @param array $arr
* @return string
*/
protected function getArrayString($arr)
{
if (!is_array($arr)) {
return $arr;
}
$stringArr = [];
foreach ($arr as $k => $v) {
$is_var = in_array(substr($v, 0, 1), ['$', '_']);
if (!$is_var) {
$v = str_replace("'", "\'", $v);
$k = str_replace("'", "\'", $k);
}
$stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
}
return implode(", ", $stringArr);
}
protected function getItemArray($item, $field, $comment)
{
$itemArr = [];
$comment = str_replace(',', ',', $comment);
if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
list($fieldLang, $item) = explode(':', $comment);
$itemArr = [];
foreach (explode(',', $item) as $k => $v) {
$valArr = explode('=', $v);
if (count($valArr) == 2) {
list($key, $value) = $valArr;
$itemArr[$key] = $field . ' ' . $key;
}
}
} else {
foreach ($item as $k => $v) {
$itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
}
}
return $itemArr;
}
protected function getFieldType(& $v)
{
$inputType = 'text';
switch ($v['DATA_TYPE']) {
case 'bigint':
case 'int':
case 'mediumint':
case 'smallint':
case 'tinyint':
$inputType = 'number';
break;
case 'enum':
case 'set':
$inputType = 'select';
break;
case 'decimal':
case 'double':
case 'float':
$inputType = 'number';
break;
case 'longtext':
case 'text':
case 'mediumtext':
case 'smalltext':
case 'tinytext':
$inputType = 'textarea';
break;
case 'year':
case 'date':
case 'time':
case 'datetime':
case 'timestamp':
$inputType = 'datetime';
break;
default:
break;
}
$fieldsName = $v['COLUMN_NAME'];
// 指定后缀说明也是个时间字段
if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
$inputType = 'datetime';
}
// 指定后缀结尾且类型为enum,说明是个单选框
if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
$inputType = "radio";
}
// 指定后缀结尾且类型为set,说明是个复选框
if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
$inputType = "checkbox";
}
// 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
$inputType = "switch";
}
// 指定后缀结尾城市选择框
if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
$inputType = "citypicker";
}
// 指定后缀结尾JSON配置
if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
$inputType = "fieldlist";
}
return $inputType;
}
/**
* 判断是否符合指定后缀
* @param string $field 字段名称
* @param mixed $suffixArr 后缀
* @return boolean
*/
protected function isMatchSuffix($field, $suffixArr)
{
$suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
foreach ($suffixArr as $k => $v) {
if (preg_match("/{$v}$/i", $field)) {
return true;
}
}
return false;
}
/**
* 获取表单分组数据
* @param string $field
* @param string $content
* @return string
*/
protected function getFormGroup($field, $content)
{
$langField = mb_ucfirst($field);
return <<<EOD
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
<div class="col-xs-12 col-sm-8">
{$content}
</div>
</div>
EOD;
}
/**
* 获取图片模板数据
* @param string $field
* @param string $content
* @return string
*/
protected function getImageUpload($field, $content)
{
$uploadfilter = $selectfilter = '';
if ($this->isMatchSuffix($field, $this->imageField)) {
$uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
$selectfilter = ' data-mimetype="image/*"';
}
$multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
$preview = ' data-preview-id="p-' . $field . '"';
$previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
return <<<EOD
<div class="input-group">
{$content}
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
<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>
</div>
<span class="msg-box n-right" for="c-{$field}"></span>
</div>
{$previewcontainer}
EOD;
}
/**
* 获取JS列数据
* @param string $field
* @param string $datatype
* @param string $extend
* @param array $itemArr
* @return string
*/
protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
{
$lang = mb_ucfirst($field);
$formatter = '';
foreach ($this->fieldFormatterSuffix as $k => $v) {
if (preg_match("/{$k}$/i", $field)) {
if (is_array($v)) {
if (in_array($datatype, $v['type'])) {
$formatter = $v['name'];
break;
}
} else {
$formatter = $v;
break;
}
}
}
$html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
if ($datatype == 'set') {
$formatter = 'label';
}
foreach ($itemArr as $k => &$v) {
if (substr($v, 0, 3) !== '__(') {
$v = "__('" . mb_ucfirst($v) . "')";
}
}
unset($v);
$searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
$searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
if ($itemArr) {
$html .= ", searchList: " . $searchList;
}
if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
$html .= ", operate:'RANGE', addclass:'datetimerange'";
} elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
$html .= ", operate:'BETWEEN'";
}
if (in_array($datatype, ['set'])) {
$html .= ", operate:'FIND_IN_SET'";
}
if (in_array($formatter, ['image', 'images'])) {
$html .= ", events: Table.api.events.image";
}
if ($itemArr && !$formatter) {
$formatter = 'normal';
}
if ($formatter) {
$html .= ", formatter: Table.api.formatter." . $formatter . "}";
} else {
$html .= "}";
}
return $html;
}
protected function getCamelizeName($uncamelized_words, $separator = '_')
{
$uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
}
protected function getFieldListName($field)
{
return $this->getCamelizeName($field) . 'List';
}
}
... ...
<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
{%addList%}
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<?php
namespace {%controllerNamespace%};
use app\common\controller\Backend;
/**
* {%tableComment%}
*
* @icon {%iconName%}
*/
class {%controllerName%} extends Backend
{
/**
* {%modelName%}模型对象
* @var \{%modelNamespace%}\{%modelName%}
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \{%modelNamespace%}\{%modelName%};
{%controllerAssignList%}
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
{%controllerIndex%}
}
... ...
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = {%relationSearch%};
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax())
{
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField'))
{
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$total = $this->model
{%relationWithList%}
->where($where)
->order($sort, $order)
->count();
$list = $this->model
{%relationWithList%}
->where($where)
->order($sort, $order)
->limit($offset, $limit)
->select();
foreach ($list as $row) {
{%visibleFieldList%}
{%relationVisibleFieldList%}
}
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
return json($result);
}
return $this->view->fetch();
}
\ No newline at end of file
... ...
<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
{%editList%}
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<div class="checkbox">
{foreach name="{%fieldList%}" item="vo"}
<label for="{%fieldName%}-{$key}"><input id="{%fieldName%}-{$key}" name="{%fieldName%}" type="checkbox" value="{$key}" {in name="key" value="{%selectedValue%}"}checked{/in} /> {$vo}</label>
{/foreach}
</div>
... ...
<dl class="fieldlist" data-name="{%fieldName%}">
<dd>
<ins>{:__('{%itemKey%}')}</ins>
<ins>{:__('{%itemValue%}')}</ins>
</dd>
<dd><a href="javascript:;" class="btn btn-sm btn-success btn-append"><i class="fa fa-plus"></i> {:__('Append')}</a></dd>
<textarea name="{%fieldName%}" class="form-control hide" cols="30" rows="5">{%fieldValue%}</textarea>
</dl>
... ...
<div class="panel-heading">
{:build_heading(null,FALSE)}
<ul class="nav nav-tabs" data-field="{%field%}">
<li class="active"><a href="#t-all" data-value="" data-toggle="tab">{:__('All')}</a></li>
{foreach name="{%fieldName%}List" item="vo"}
<li><a href="#t-{$key}" data-value="{$key}" data-toggle="tab">{$vo}</a></li>
{/foreach}
</ul>
</div>
... ...
<div class="radio">
{foreach name="{%fieldList%}" item="vo"}
<label for="{%fieldName%}-{$key}"><input id="{%fieldName%}-{$key}" name="{%fieldName%}" type="radio" value="{$key}" {in name="key" value="{%selectedValue%}"}checked{/in} /> {$vo}</label>
{/foreach}
</div>
... ...
<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>
\ No newline at end of file
... ...
<select {%attrStr%}>
{foreach name="{%fieldList%}" item="vo"}
<option value="{$key}" {in name="key" value="{%selectedValue%}"}selected{/in}>{$vo}</option>
{/foreach}
</select>
... ...
<input {%attrStr%} name="{%fieldName%}" type="hidden" value="{%fieldValue%}">
<a href="javascript:;" data-toggle="switcher" class="btn-switcher" data-input-id="c-{%field%}" data-yes="{%fieldYes%}" data-no="{%fieldNo%}" >
<i class="fa fa-toggle-on text-success {%fieldSwitchClass%} fa-2x"></i>
</a>
\ No newline at end of file
... ...
<div class="panel panel-default panel-intro">
{%headingHtml%}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
<a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
<a href="javascript:;" class="btn btn-success btn-add {:$auth->check('{%controllerUrl%}/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
<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>
<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>
<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>
<div class="dropdown btn-group {:$auth->check('{%controllerUrl%}/multi')?'':'hide'}">
<a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> {:__('More')}</a>
<ul class="dropdown-menu text-left" role="menu">
<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>
<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>
</ul>
</div>
{%recyclebinHtml%}
</div>
<table id="table" class="table table-striped table-bordered table-hover table-nowrap"
data-operate-edit="{:$auth->check('{%controllerUrl%}/edit')}"
data-operate-del="{:$auth->check('{%controllerUrl%}/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: '{%controllerUrl%}/index' + location.search,
add_url: '{%controllerUrl%}/add',
edit_url: '{%controllerUrl%}/edit',
del_url: '{%controllerUrl%}/del',
multi_url: '{%controllerUrl%}/multi',
table: '{%table%}',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: '{%pk%}',
sortName: '{%order%}',
columns: [
[
{%javascriptList%}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},{%recyclebinJs%}
add: function () {
Controller.api.bindevent();
},
edit: function () {
Controller.api.bindevent();
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
}
}
};
return Controller;
});
\ No newline at end of file
... ...
<?php
return [
{%langList%}
];
... ...
public function {%methodName%}($value, $data)
{
$value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
$valueArr = explode(',', $value);
$list = $this->{%listMethodName%}();
return implode(',', array_intersect_key($list, array_flip($valueArr)));
}
\ No newline at end of file
... ...
public function {%methodName%}($value, $data)
{
$value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
\ No newline at end of file
... ...
protected static function init()
{
self::afterInsert(function ($row) {
$pk = $row->getPk();
$row->getQuery()->where($pk, $row[$pk])->update(['{%order%}' => $row[$pk]]);
});
}
... ...
public function {%relationMethod%}()
{
return $this->{%relationMode%}('{%relationClassName%}', '{%relationForeignKey%}', '{%relationPrimaryKey%}', [], 'LEFT')->setEagerlyType(0);
}
\ No newline at end of file
... ...
public function {%methodName%}($value, $data)
{
$value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
$valueArr = explode(',', $value);
$list = $this->{%listMethodName%}();
return implode(',', array_intersect_key($list, array_flip($valueArr)));
}
\ No newline at end of file
... ...
public function {%methodName%}($value, $data)
{
$value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
$list = $this->{%listMethodName%}();
return isset($list[$value]) ? $list[$value] : '';
}
\ No newline at end of file
... ...
recyclebin: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
'dragsort_url': ''
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: '{%controllerUrl%}/recyclebin' + location.search,
pk: 'id',
sortName: 'id',
columns: [
[
{checkbox: true},
{field: 'id', title: __('Id')},{%recyclebinTitleJs%}
{
field: 'deletetime',
title: __('Deletetime'),
operate: 'RANGE',
addclass: 'datetimerange',
formatter: Table.api.formatter.datetime
},
{
field: 'operate',
width: '130px',
title: __('Operate'),
table: table,
events: Table.api.events.operate,
buttons: [
{
name: 'Restore',
text: __('Restore'),
classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
icon: 'fa fa-rotate-left',
url: '{%controllerUrl%}/restore',
refresh: true
},
{
name: 'Destroy',
text: __('Destroy'),
classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
icon: 'fa fa-times',
url: '{%controllerUrl%}/destroy',
refresh: true
}
],
formatter: Table.api.formatter.operate
}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
\ No newline at end of file
... ...
public function {%methodName%}($value, $data)
{
$value = $value ? $value : (isset($data['{%field%}']) ? $data['{%field%}'] : '');
$list = $this->{%listMethodName%}();
return isset($list[$value]) ? $list[$value] : '';
}
\ No newline at end of file
... ...
<?php
namespace {%modelNamespace%};
use think\Model;
{%sofeDeleteClassPath%}
class {%modelName%} extends Model
{
{%softDelete%}
{%modelConnection%}
// 表名
protected ${%modelTableType%} = '{%modelTableTypeName%}';
// 自动写入时间戳字段
protected $autoWriteTimestamp = {%modelAutoWriteTimestamp%};
// 定义时间戳字段名
protected $createTime = {%createTime%};
protected $updateTime = {%updateTime%};
protected $deleteTime = {%deleteTime%};
// 追加属性
protected $append = [
{%appendAttrList%}
];
{%modelInit%}
{%getEnumList%}
{%getAttrList%}
{%setAttrList%}
{%relationMethodList%}
}
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
{:build_toolbar('refresh')}
<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>
<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>
<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>
<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>
</div>
<table id="table" class="table table-striped table-bordered table-hover"
data-operate-restore="{:$auth->check('{%controllerUrl%}/restore')}"
data-operate-destroy="{:$auth->check('{%controllerUrl%}/destroy')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
<?php
namespace {%modelNamespace%};
use think\Model;
class {%relationName%} extends Model
{
// 表名
protected ${%relationTableType%} = '{%relationTableTypeName%}';
}
... ...
<?php
namespace {%validateNamespace%};
use think\Validate;
class {%validateName%} extends Validate
{
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}
... ...
<?php
namespace app\admin\command;
use PDO;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
class Install extends Command
{
protected $model = null;
protected function configure()
{
$config = Config::get('database');
$this
->setName('install')
->addOption('hostname', 'a', Option::VALUE_OPTIONAL, 'mysql hostname', $config['hostname'])
->addOption('hostport', 'o', Option::VALUE_OPTIONAL, 'mysql hostport', $config['hostport'])
->addOption('database', 'd', Option::VALUE_OPTIONAL, 'mysql database', $config['database'])
->addOption('prefix', 'r', Option::VALUE_OPTIONAL, 'table prefix', $config['prefix'])
->addOption('username', 'u', Option::VALUE_OPTIONAL, 'mysql username', $config['username'])
->addOption('password', 'p', Option::VALUE_OPTIONAL, 'mysql password', $config['password'])
->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', false)
->setDescription('New installation of FastAdmin');
}
protected function execute(Input $input, Output $output)
{
// 覆盖安装
$force = $input->getOption('force');
$hostname = $input->getOption('hostname');
$hostport = $input->getOption('hostport');
$database = $input->getOption('database');
$prefix = $input->getOption('prefix');
$username = $input->getOption('username');
$password = $input->getOption('password');
$installLockFile = __DIR__ . "/Install/install.lock";
if (is_file($installLockFile) && !$force) {
throw new Exception("\nFastAdmin already installed!\nIf you need to reinstall again, use the parameter --force=true ");
}
$sql = file_get_contents(__DIR__ . '/Install/fastadmin.sql');
$sql = str_replace("`fa_", "`{$prefix}", $sql);
// 先尝试能否自动创建数据库
$config = Config::get('database');
$pdo = new PDO("{$config['type']}:host={$hostname}" . ($hostport ? ";port={$hostport}" : ''), $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query("CREATE DATABASE IF NOT EXISTS `{$database}` CHARACTER SET utf8 COLLATE utf8_general_ci;");
// 连接install命令中指定的数据库
$instance = Db::connect([
'type' => "{$config['type']}",
'hostname' => "{$hostname}",
'hostport' => "{$hostport}",
'database' => "{$database}",
'username' => "{$username}",
'password' => "{$password}",
]);
// 查询一次SQL,判断连接是否正常
$instance->execute("SELECT 1");
// 调用原生PDO对象进行批量查询
$instance->getPdo()->exec($sql);
file_put_contents($installLockFile, 1);
//后台入口文件
$adminFile = ROOT_PATH . 'public' . DS . 'admin.php';
$dbConfigFile = APP_PATH . 'database.php';
$config = @file_get_contents($dbConfigFile);
$callback = function ($matches) use ($hostname, $hostport, $username, $password, $database, $prefix) {
$field = $matches[1];
$replace = $$field;
if ($matches[1] == 'hostport' && $hostport == 3306) {
$replace = '';
}
return "'{$matches[1]}'{$matches[2]}=>{$matches[3]}Env::get('database.{$matches[1]}', '{$replace}'),";
};
$config = preg_replace_callback("/'(hostname|database|username|password|hostport|prefix)'(\s+)=>(\s+)Env::get\((.*)\)\,/", $callback, $config);
// 写入数据库配置
file_put_contents($dbConfigFile, $config);
// 修改后台入口
if (is_file($adminFile)) {
$x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$adminName = substr(str_shuffle(str_repeat($x, ceil(10 / strlen($x)))), 1, 10) . '.php';
rename($adminFile, ROOT_PATH . 'public' . DS . $adminName);
$output->highlight("Admin url:http://www.yoursite.com/{$adminName}");
}
$output->highlight("Admin username:admin");
$output->highlight("Admin password:123456");
\think\Cache::rm('__menu__');
$output->info("Install Successed!");
}
}
... ...