Crud.php 16 KB

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