CodeGeneration.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2019/12/5
  6. * Time: 17:44
  7. */
  8. namespace app\admin\controller;
  9. use app\admin\controller\base\Permissions;
  10. use file\FileHelper;
  11. use think\Db;
  12. class CodeGeneration extends Permissions
  13. {
  14. /**
  15. * @return mixed
  16. */
  17. public function index()
  18. {
  19. $dbName = \think\Env::get("db_name", "");
  20. $prefix = \think\Env::get("db_prefix", "");
  21. //排除核心表
  22. $coreTables = ['admin', 'admin_cate', 'admin_log', 'admin_menu', 'urlconfig', 'webconfig', 'smsconfig', 'emailconfig', 'config', 'config_option', 'config_tab', 'catalog', 'cate_catalog'];
  23. $filters = [];
  24. foreach ($coreTables as $table) {
  25. $filters[] = "'{$prefix}{$table}'";
  26. }
  27. $filter = implode(',', $filters);
  28. $tables = Db::query("SELECT TABLE_NAME,TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME NOT IN ($filter)", [$dbName]);
  29. $this->assign('tables', $tables);
  30. return $this->fetch();
  31. }
  32. /**
  33. * 获取字段信息
  34. * @return array
  35. */
  36. public function getFieldsInfo()
  37. {
  38. if ($this->request->isAjax()) {
  39. $post = $this->request->param();
  40. $validate = new \think\Validate([
  41. ['table', 'require|max:50', '请选择数据库表'],
  42. ]);
  43. if (!$validate->check($post)) {
  44. $this->error('提交失败:' . $validate->getError());
  45. }
  46. $nameAndComment = explode('|', $post['table']);
  47. $tableName = $nameAndComment[0]??'';
  48. $data = $this->getFieldsInfoByTableName($tableName);
  49. return array('code' => 0, 'count' => count($data), 'data' => $data);
  50. }
  51. }
  52. /**
  53. * 生成
  54. */
  55. public function generation()
  56. {
  57. $post = $this->request->post();
  58. if ($this->request->isPost()) {
  59. $validate = new \think\Validate([
  60. ['table', 'require|max:50', '请选择数据库表'],
  61. ]);
  62. if (!$validate->check($post)) {
  63. $this->error('提交失败:' . $validate->getError());
  64. }
  65. }
  66. $nameAndComment = explode('|', $post['table']);
  67. $tableName = $nameAndComment[0]??'';
  68. $menuName = $nameAndComment[1] ?: $tableName;
  69. $humpName = $this->getHumpName($tableName);
  70. $underLineName = $this->getUnderLineName($tableName);
  71. $fieldsInfo = $this->getFieldsInfoByTableName($tableName);
  72. foreach ($fieldsInfo as $k => $item) {
  73. $field = $item['Field'];
  74. $fieldsInfo[$k]["ShowList"] = $post[$field . "_ShowList"]??'';
  75. $fieldsInfo[$k]["ShowSearch"] = $post[$field . "_ShowSearch"]??'';
  76. $fieldsInfo[$k]["ShowEdit"] = $post[$field . "_ShowEdit"]??'';
  77. $fieldsInfo[$k]["Component"] = $post[$field . "_Component"];
  78. }
  79. $tpData = [
  80. 'fieldsInfo' => $fieldsInfo,
  81. 'humpName' => $humpName,
  82. 'underLineName' => $underLineName,
  83. 'menuName' => $menuName,
  84. 'tableName' => $tableName,
  85. 'crud' => $post['crud']??[],
  86. ];
  87. //模板文件目录
  88. $tpdir = APP_PATH . 'admin' . DS . 'view' . DS . 'code_generation' . DS . 'tpl' . DS;
  89. //生成文件路径
  90. $ControllerPath = APP_PATH . 'admin' . DS . 'controller' . DS . $humpName . '.php';
  91. $ModelPath = APP_PATH . 'common' . DS . 'model' . DS . $humpName . '.php';
  92. $IndexPath = APP_PATH . 'admin' . DS . 'view' . DS . $underLineName . DS . 'index.html';
  93. $PublishPaht = APP_PATH . 'admin' . DS . 'view' . DS . $underLineName . DS . 'publish.html';
  94. if (!$this->request->has('cover')) {
  95. //检查文件是否已存在
  96. $checkMsg = "";
  97. if (file_exists($ControllerPath)) {
  98. $checkMsg .= str_replace(APP_PATH, '', $ControllerPath) . " 已存在" . '</br>';
  99. }
  100. if (file_exists($ModelPath)) {
  101. $checkMsg .= str_replace(APP_PATH, '', $ModelPath) . " 已存在" . '</br>';
  102. }
  103. if (file_exists($IndexPath)) {
  104. $checkMsg .= str_replace(APP_PATH, '', $IndexPath) . " 已存在" . '</br>';
  105. }
  106. if (array_key_exists('update', $tpData['crud']) or array_key_exists('create', $tpData['crud'])) {
  107. if (file_exists($PublishPaht)) {
  108. $checkMsg .= str_replace(APP_PATH, '', $PublishPaht) . " 已存在" . '</br>';
  109. }
  110. }
  111. if (!empty($checkMsg)) {
  112. $checkMsg .= "<span style='color:red;'>确认生成并覆盖?</span>";
  113. $this->error($checkMsg);
  114. }
  115. }
  116. //生成controller
  117. $content = $this->fetch($tpdir . 'AdminController.php.tp', $tpData);
  118. FileHelper::save($ControllerPath, "<?php" . PHP_EOL . $content);
  119. //生成model
  120. $content = $this->fetch($tpdir . 'Model.php.tp', $tpData);
  121. FileHelper::save($ModelPath, "<?php" . PHP_EOL . $content);
  122. //生成index.html
  123. $content = $this->fetch($tpdir . 'index.html.tp', $tpData);
  124. FileHelper::save($IndexPath, $content);
  125. //生成publish.html
  126. if (array_key_exists('update', $tpData['crud']) or array_key_exists('create', $tpData['crud'])) {
  127. $content = $this->fetch($tpdir . 'publish.html.tp', $tpData);
  128. FileHelper::save($PublishPaht, $content);
  129. }
  130. $this->success("success");
  131. }
  132. /**
  133. * 表名 转 驼峰命名
  134. * @param $tableName
  135. * @return string
  136. */
  137. protected function getHumpName($tableName)
  138. {
  139. $db_prefix = \think\Env::get("db_prefix", "");
  140. //去除表前缀
  141. $tableName = str_replace($db_prefix, '', $tableName);
  142. //拆分,首字母大写
  143. $trems = explode('_', $tableName);
  144. $controllerName = "";
  145. foreach ($trems as $trem) {
  146. $controllerName .= ucfirst($trem);
  147. }
  148. return $controllerName ?: 'DefaultController';
  149. }
  150. /**
  151. * 表名 转 下划线命名
  152. * @param $tableName
  153. * @return mixed
  154. */
  155. protected function getUnderLineName($tableName)
  156. {
  157. //去除表前缀即可
  158. $db_prefix = \think\Env::get("db_prefix", "");
  159. return str_replace($db_prefix, '', $tableName);
  160. }
  161. /**
  162. * 获取字段信息
  163. * @param $tableName
  164. * @return array
  165. */
  166. protected function getFieldsInfoByTableName($tableName)
  167. {
  168. $dbName = \think\Env::get("db_name", "");
  169. //读取字段信息
  170. $infos = Db::query("desc " . $tableName);
  171. //读取字段注释
  172. $comments = Db::query("SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME=? AND table_schema=?", [$tableName, $dbName]);
  173. $data = [];
  174. foreach ($infos as $k => $info) {
  175. $data[$info['Field']] = $info;
  176. $data[$info['Field']]['Comment'] = $comments[$k]['column_comment'];//这里不能保证两个数组顺序一致,后期有问题再修改
  177. }
  178. return $data;
  179. }
  180. }