Crud.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. namespace app\admin\command;
  3. use fast\Form;
  4. use think\Config;
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\input\Option;
  8. use think\console\Output;
  9. use think\Db;
  10. use think\Lang;
  11. class Crud extends Command
  12. {
  13. protected function configure()
  14. {
  15. $this
  16. ->setName('crud')
  17. ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
  18. ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
  19. ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
  20. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
  21. ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
  22. ->setDescription('Build CRUD controller and model from table');
  23. }
  24. protected function execute(Input $input, Output $output)
  25. {
  26. $adminPath = dirname(__DIR__) . DS;
  27. //表名
  28. $table = $input->getOption('table') ? : '';
  29. //自定义控制器
  30. $controller = $input->getOption('controller');
  31. //自定义模型
  32. $model = $input->getOption('model');
  33. //强制覆盖
  34. $force = $input->getOption('force');
  35. //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
  36. $local = $input->getOption('local');
  37. if (!$table)
  38. {
  39. $output->error('table name can\'t empty');
  40. return;
  41. }
  42. $dbname = Config::get('database.database');
  43. $prefix = Config::get('database.prefix');
  44. $tableName = $prefix . $table;
  45. $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
  46. if (!$tableInfo)
  47. {
  48. $output->error("table not found");
  49. return;
  50. }
  51. $tableInfo = $tableInfo[0];
  52. //根据表名匹配对应的Fontawesome图标
  53. $iconPath = ROOT_PATH . '/public/assets/libs/font-awesome/less/variables.less';
  54. $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? $table : 'fa fa-circle-o';
  55. //控制器默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入controller,格式为目录层级
  56. $controllerArr = !$controller ? explode('_', strtolower($table)) : explode('/', strtolower($controller));
  57. $controllerUrl = implode('/', $controllerArr);
  58. $controllerName = ucfirst(array_pop($controllerArr));
  59. $controllerDir = implode('/', $controllerArr);
  60. $controllerFile = ($controllerDir ? $controllerDir . '/' : '') . $controllerName . '.php';
  61. //非覆盖模式时如果存在控制器文件则报错
  62. if (is_file($controllerFile) && !$force)
  63. {
  64. $output->error('controller already exists');
  65. return;
  66. }
  67. //模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入model,不支持目录层级
  68. if (!$model)
  69. {
  70. $modelarr = explode('_', strtolower($table));
  71. foreach ($modelarr as $k => &$v)
  72. $v = ucfirst($v);
  73. unset($v);
  74. $modelName = implode('', $modelarr);
  75. }
  76. else
  77. {
  78. $modelName = ucfirst($model);
  79. }
  80. $modelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $modelName . '.php';
  81. //非覆盖模式时如果存在模型文件则报错
  82. if (is_file($modelFile) && !$force)
  83. {
  84. $output->error('model already exists');
  85. return;
  86. }
  87. //从数据库中获取表字段信息
  88. $columnList = Db::query("SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION", [$dbname, $tableName]);
  89. $fields = [];
  90. foreach ($columnList as $k => $v)
  91. {
  92. $fields[] = $v['COLUMN_NAME'];
  93. }
  94. $addList = [];
  95. $editList = [];
  96. $javascriptList = [];
  97. $langList = [];
  98. $field = 'id';
  99. $order = 'id';
  100. //循环所有字段,开始构造视图的HTML和JS信息
  101. foreach ($columnList as $k => $v)
  102. {
  103. $field = $v['COLUMN_NAME'];
  104. $fieldLang = ucfirst($field);
  105. // 语言列表
  106. if ($v['COLUMN_COMMENT'] != '')
  107. {
  108. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  109. }
  110. if ($v['COLUMN_KEY'] != 'PRI')
  111. {
  112. $inputType = 'text';
  113. $step = 0;
  114. switch ($v['DATA_TYPE'])
  115. {
  116. case 'bigint':
  117. case 'int':
  118. case 'mediumint':
  119. case 'smallint':
  120. case 'tinyint':
  121. $inputType = 'number';
  122. break;
  123. case 'enum':
  124. case 'set':
  125. $inputType = 'select';
  126. break;
  127. case 'decimal':
  128. case 'double':
  129. case 'float':
  130. $inputType = 'number';
  131. $step = "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1";
  132. case 'text':
  133. $inputType = 'textarea';
  134. default:
  135. break;
  136. }
  137. if (substr($field, -4) == 'time')
  138. {
  139. $inputType = 'datetime';
  140. }
  141. if ($inputType == 'select')
  142. {
  143. $itemlist = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  144. $itemlist = str_replace("'", '', $itemlist);
  145. $attr = "'id'=>'c-$field','class'=>'form-control selectpicker'";
  146. if ($v['DATA_TYPE'] == 'enum')
  147. {
  148. $attr .= ",'multiple'=>''";
  149. }
  150. if ($v['COLUMN_DEFAULT'] == '')
  151. {
  152. $attr .= ",'required'=>''";
  153. }
  154. $formAddElement = "{:build_select('row[$field]', '{$itemlist}', null, [{$attr}])}";
  155. $formEditElement = "{:build_select('row[$field]', '{$itemlist}', \$row['$field'], [{$attr}])}";
  156. }
  157. else
  158. {
  159. //CSS类名
  160. $cssClass = ['form-control'];
  161. $cssClass[] = substr($field, -4) == 'time' ? 'datetimepicker' : '';
  162. $cssClass[] = $v['DATA_TYPE'] == 'text' ? 'summernote' : '';
  163. $cssClass[] = substr($field, -3) == '_id' ? 'typeahead' : '';
  164. $cssClass[] = substr($field, -4) == '_ids' ? 'tagsinput' : '';
  165. $cssClass = array_filter($cssClass);
  166. //因为有自动完成可输入其它内容
  167. if (array_intersect($cssClass, ['typeahead', 'tagsinput']))
  168. {
  169. $inputType = 'text';
  170. $step = 0;
  171. }
  172. $attr = ['id' => "c-{$field}", 'class' => implode(' ', $cssClass)];
  173. if ($step)
  174. {
  175. $attr['step'] = $step;
  176. }
  177. //如果是图片则额外附加
  178. if (substr($field, -5) == 'image' || substr($field, -6) == 'avatar')
  179. {
  180. $attr['data-plupload-id'] = "plupload-{$field}-text";
  181. $attr['size'] = 50;
  182. }
  183. $fieldFunc = substr($field, -4) == 'time' ? "|datetime" : "";
  184. if ($inputType == 'textarea')
  185. {
  186. $formAddElement = Form::textarea("row[{$field}]", $v['COLUMN_DEFAULT'], $attr);
  187. $formEditElement = Form::textarea("row[{$field}]", "{\$row.{$field}{$fieldFunc}}", $attr);
  188. }
  189. else
  190. {
  191. $formAddElement = Form::input($inputType, "row[{$field}]", $v['COLUMN_DEFAULT'], $attr);
  192. $formEditElement = Form::input($inputType, "row[{$field}]", "{\$row.{$field}{$fieldFunc}}", $attr);
  193. }
  194. if (substr($field, -5) == 'image' || substr($field, -6) == 'avatar')
  195. {
  196. //如果是图片或头像
  197. $formAddElement = $this->getImageUpload($field, $formAddElement);
  198. $formEditElement = $this->getImageUpload($field, $formEditElement);
  199. }
  200. else if ($field == 'status')
  201. {
  202. //如果是状态字段
  203. $formAddElement = "{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')])}";
  204. $formEditElement = "{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')], \$row['status'])}";
  205. }
  206. }
  207. //构造添加和编辑HTML信息
  208. $addList[] = $this->getFormGroup($field, $formAddElement);
  209. $editList[] = $this->getFormGroup($field, $formEditElement);
  210. }
  211. //过滤text类型字段
  212. if ($v['DATA_TYPE'] != 'text')
  213. {
  214. //主键
  215. if ($v['COLUMN_KEY'] == 'PRI')
  216. {
  217. $javascriptList[] = "{field: 'state', checkbox: true}";
  218. }
  219. //构造JS列信息
  220. $javascriptList[] = $this->getJsColumn($field);
  221. //排序方式,如果有weigh则按weigh,否则按主键排序
  222. $order = $field == 'weigh' ? 'weigh' : $order;
  223. }
  224. }
  225. //JS最后一列加上操作列
  226. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  227. $addList = implode("\n", array_filter($addList));
  228. $editList = implode("\n", array_filter($editList));
  229. $javascriptList = implode(",\n", array_filter($javascriptList));
  230. $langList = implode(",\n", array_filter($langList));
  231. //表注释
  232. $tableComment = $tableInfo['Comment'];
  233. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  234. //最终将生成的文件路径
  235. $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
  236. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
  237. $addFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'add.html';
  238. $editFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'edit.html';
  239. $indexFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'index.html';
  240. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
  241. $appNamespace = Config::get('app_namespace');
  242. $moduleName = 'admin';
  243. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  244. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  245. $data = [
  246. 'controllerNamespace' => $controllerNamespace,
  247. 'modelNamespace' => $modelNamespace,
  248. 'controllerUrl' => $controllerUrl,
  249. 'controllerDir' => $controllerDir,
  250. 'controllerName' => $controllerName,
  251. 'modelName' => $modelName,
  252. 'tableComment' => $tableComment,
  253. 'iconName' => $iconName,
  254. 'order' => $order,
  255. 'table' => $table,
  256. 'tableName' => $tableName,
  257. 'addList' => $addList,
  258. 'editList' => $editList,
  259. 'javascriptList' => $javascriptList,
  260. 'langList' => $langList,
  261. 'modelAutoWriteTimestamp' => in_array('createtime', $fields) || in_array('updatetime', $fields) ? "'int'" : 'false',
  262. 'createTime' => in_array('createtime', $fields) ? "'createtime'" : 'false',
  263. 'updateTime' => in_array('updatetime', $fields) ? "'updatetime'" : 'false',
  264. ];
  265. // 生成控制器文件
  266. $result = $this->writeToFile('controller', $data, $controllerFile);
  267. // 生成模型文件
  268. $result = $this->writeToFile('model', $data, $modelFile);
  269. // 生成视图文件
  270. $result = $this->writeToFile('add', $data, $addFile);
  271. $result = $this->writeToFile('edit', $data, $editFile);
  272. $result = $this->writeToFile('index', $data, $indexFile);
  273. // 生成JS文件
  274. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  275. // 生成语言文件
  276. if ($langList)
  277. {
  278. $result = $this->writeToFile('lang', $data, $langFile);
  279. }
  280. $output->writeln("<info>Build Successed</info>");
  281. }
  282. /**
  283. * 写入到文件
  284. * @param string $name
  285. * @param array $data
  286. * @param string $pathname
  287. * @return mixed
  288. */
  289. protected function writeToFile($name, $data, $pathname)
  290. {
  291. $search = $replace = [];
  292. foreach ($data as $k => $v)
  293. {
  294. $search[] = "{%{$k}%}";
  295. $replace[] = $v;
  296. }
  297. $stub = file_get_contents($this->getStub($name));
  298. $content = str_replace($search, $replace, $stub);
  299. if (!is_dir(dirname($pathname)))
  300. {
  301. mkdir(strtolower(dirname($pathname)), 0755, true);
  302. }
  303. return file_put_contents($pathname, $content);
  304. }
  305. /**
  306. * 获取基础模板
  307. * @param string $name
  308. * @return string
  309. */
  310. protected function getStub($name)
  311. {
  312. return __DIR__ . '/Crud/stubs/' . $name . '.stub';
  313. }
  314. protected function getLangItem($field, $content)
  315. {
  316. if (!Lang::has($field))
  317. {
  318. return <<<EOD
  319. '{$field}' => '{$content}'
  320. EOD;
  321. }
  322. else
  323. {
  324. return '';
  325. }
  326. }
  327. /**
  328. * 获取表单分组数据
  329. * @param string $field
  330. * @param string $content
  331. * @return string
  332. */
  333. protected function getFormGroup($field, $content)
  334. {
  335. $langField = ucfirst($field);
  336. return<<<EOD
  337. <div class="form-group">
  338. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  339. <div class="col-xs-12 col-sm-8">
  340. {$content}
  341. </div>
  342. </div>
  343. EOD;
  344. }
  345. /**
  346. * 获取图片模板数据
  347. * @param string $field
  348. * @param string $content
  349. * @return array
  350. */
  351. protected function getImageUpload($field, $content)
  352. {
  353. return <<<EOD
  354. <div class="form-inline">
  355. {$content}
  356. <span><button id="plupload-{$field}" class="btn btn-danger plupload" ><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  357. </div>
  358. EOD;
  359. }
  360. /**
  361. * 获取JS列数据
  362. * @param string $field
  363. * @return string
  364. */
  365. protected function getJsColumn($field)
  366. {
  367. $lang = ucfirst($field);
  368. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  369. $formatter = '';
  370. if ($field == 'status')
  371. $formatter = 'status';
  372. else if ($field == 'icon')
  373. $formatter = 'icon';
  374. else if ($field == 'flag')
  375. $formatter = 'flag';
  376. else if (substr($field, -4) == 'time')
  377. $formatter = 'datetime';
  378. else if (substr($field, -3) == 'url')
  379. $formatter = 'url';
  380. else if (substr($field, -5) == 'image')
  381. $formatter = 'image';
  382. if ($formatter)
  383. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  384. else
  385. $html .= "}";
  386. return $html;
  387. }
  388. }