Crud.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 . str_replace('/', DS, '/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(DS, $controllerArr);
  59. $controllerFile = ($controllerDir ? $controllerDir . DS : '') . $controllerName . '.php';
  60. //非覆盖模式时如果存在控制器文件则报错
  61. if (is_file($controllerFile) && !$force)
  62. {
  63. throw new Exception('controller already exists!\nIf you need to rebuild again, use the parameter --force=true ');
  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!\nIf you need to rebuild again, use the parameter --force=true ');
  83. }
  84. require $adminPath . 'common.php';
  85. //从数据库中获取表字段信息
  86. $columnList = Db::query("SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND table_name = ? ORDER BY ORDINAL_POSITION", [$dbname, $tableName]);
  87. $fields = [];
  88. foreach ($columnList as $k => $v)
  89. {
  90. $fields[] = $v['COLUMN_NAME'];
  91. }
  92. $addList = [];
  93. $editList = [];
  94. $javascriptList = [];
  95. $langList = [];
  96. $field = 'id';
  97. $order = 'id';
  98. $priDefined = FALSE;
  99. try
  100. {
  101. Form::setEscapeHtml(false);
  102. //循环所有字段,开始构造视图的HTML和JS信息
  103. foreach ($columnList as $k => $v)
  104. {
  105. $field = $v['COLUMN_NAME'];
  106. $itemArr = [];
  107. // 这里构建Enum和Set类型的列表数据
  108. if (in_array($v['DATA_TYPE'], ['enum', 'set']))
  109. {
  110. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  111. $itemArr = explode(',', str_replace("'", '', $itemArr));
  112. }
  113. // 语言列表
  114. if ($v['COLUMN_COMMENT'] != '')
  115. {
  116. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  117. }
  118. //createtime和updatetime是保留字段不能修改和添加
  119. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, ['createtime', 'updatetime']))
  120. {
  121. $inputType = $this->getFieldType($v);
  122. // 如果是number类型时增加一个步长
  123. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  124. $attrArr = ['id' => "c-{$field}"];
  125. $cssClassArr = ['form-control'];
  126. $fieldName = "row[{$field}]";
  127. $defaultValue = $v['COLUMN_DEFAULT'];
  128. $editValue = "{\$row.{$field}}";
  129. // 如果默认值为空,则是一个必选项
  130. if ($v['COLUMN_DEFAULT'] == '')
  131. {
  132. $attrArr['required'] = '';
  133. }
  134. if ($field == 'status' && in_array($inputType, ['text', 'number']))
  135. {
  136. //如果状态类型不是enum或set
  137. $itemArr = !$itemArr ? ['normal', 'hidden'] : $itemArr;
  138. $inputType = 'radio';
  139. }
  140. if ($inputType == 'select')
  141. {
  142. $cssClassArr[] = 'selectpicker';
  143. $attrArr['class'] = implode(' ', $cssClassArr);
  144. if ($v['DATA_TYPE'] == 'set')
  145. {
  146. $attrArr['multiple'] = '';
  147. $fieldName.="[]";
  148. }
  149. $attrStr = $this->getArrayString($attrArr);
  150. $itemArr = $this->getLangArray($itemArr, FALSE);
  151. $itemString = $this->getArrayString($itemArr);
  152. $formAddElement = "{:build_select('{$fieldName}', [{$itemString}], '{$defaultValue}', [{$attrStr}])}";
  153. $formEditElement = "{:build_select('{$fieldName}', [{$itemString}], \$row.{$field}, [{$attrStr}])}";
  154. }
  155. else if ($inputType == 'datetime')
  156. {
  157. $cssClassArr[] = 'datetimepicker';
  158. $attrArr['class'] = implode(' ', $cssClassArr);
  159. $format = "YYYY-MM-DD HH:mm:ss";
  160. $phpFormat = "Y-m-d H:i:s";
  161. $fieldFunc = '';
  162. switch ($v['DATA_TYPE'])
  163. {
  164. case 'year';
  165. $format = "YYYY";
  166. $phpFormat = 'Y';
  167. break;
  168. case 'date';
  169. $format = "YYYY-MM-DD";
  170. $phpFormat = 'Y-m-d';
  171. break;
  172. case 'time';
  173. $format = "HH:mm:ss";
  174. $phpFormat = 'H:i:s';
  175. break;
  176. case 'timestamp';
  177. $fieldFunc = 'datetime';
  178. case 'datetime';
  179. $format = "YYYY-MM-DD HH:mm:ss";
  180. $phpFormat = 'Y-m-d H:i:s';
  181. break;
  182. default:
  183. $fieldFunc = 'datetime';
  184. break;
  185. }
  186. $defaultDateTime = "{:date('{$phpFormat}')}";
  187. $attrArr['data-date-format'] = $format;
  188. $attrArr['data-use-current'] = "true";
  189. $fieldFunc = $fieldFunc ? "|{$fieldFunc}" : "";
  190. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  191. $formEditElement = Form::text($fieldName, "{\$row.{$field}{$fieldFunc}}", $attrArr);
  192. }
  193. else if ($inputType == 'checkbox')
  194. {
  195. $fieldName.="[]";
  196. $itemArr = $this->getLangArray($itemArr, FALSE);
  197. $itemString = $this->getArrayString($itemArr);
  198. $formAddElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
  199. $formEditElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], \$row.{$field})}";
  200. }
  201. else if ($inputType == 'radio')
  202. {
  203. $itemArr = $this->getLangArray($itemArr, FALSE);
  204. $itemString = $this->getArrayString($itemArr);
  205. $defaultValue = $defaultValue ? $defaultValue : key($itemArr);
  206. $formAddElement = "{:build_radios('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
  207. $formEditElement = "{:build_radios('{$fieldName}', [{$itemString}], \$row.{$field})}";
  208. }
  209. else if ($inputType == 'textarea' || ($inputType == 'text' && $v['CHARACTER_MAXIMUM_LENGTH'] >= 255))
  210. {
  211. $cssClassArr[] = substr($field, -7) == 'content' ? 'summernote' : '';
  212. $attrArr['class'] = implode(' ', $cssClassArr);
  213. $attrArr['rows'] = 5;
  214. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  215. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  216. }
  217. else if ($field == 'category_id' || $field == 'category_ids')
  218. {
  219. $type = $table;
  220. if ($field == 'category_ids')
  221. {
  222. $attrArr['multiple'] = '';
  223. }
  224. $attrStr = $this->getArrayString($attrArr);
  225. $formAddElement = "{:build_category_select('{$fieldName}', '{$type}', '{$defaultValue}', [{$attrStr}])}";
  226. $formEditElement = "{:build_category_select('{$fieldName}', '{$type}', \$row.{$field}, [{$attrStr}])}";
  227. }
  228. else
  229. {
  230. //CSS类名
  231. $cssClassArr[] = substr($field, -3) == '_id' ? 'typeahead' : '';
  232. $cssClassArr[] = substr($field, -4) == '_ids' ? 'tagsinput' : '';
  233. $cssClassArr = array_filter($cssClassArr);
  234. //因为有自动完成可输入其它内容
  235. $step = array_intersect($cssClassArr, ['typeahead', 'tagsinput']) ? 0 : $step;
  236. $attrArr['class'] = implode(' ', $cssClassArr);
  237. $isUpload = substr($field, -4) == 'file' || substr($field, -5) == 'image' || substr($field, -6) == 'avatar' ? TRUE : FALSE;
  238. //如果是步长则加上步长
  239. if ($step)
  240. {
  241. $attrArr['step'] = $step;
  242. }
  243. //如果是图片加上个size
  244. if ($isUpload)
  245. {
  246. $attrArr['size'] = 50;
  247. }
  248. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  249. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  250. //如果是图片或文件
  251. if ($isUpload)
  252. {
  253. $formAddElement = $this->getImageUpload($field, $formAddElement);
  254. $formEditElement = $this->getImageUpload($field, $formEditElement);
  255. }
  256. }
  257. //构造添加和编辑HTML信息
  258. $addList[] = $this->getFormGroup($field, $formAddElement);
  259. $editList[] = $this->getFormGroup($field, $formEditElement);
  260. }
  261. //过滤text类型字段
  262. if ($v['DATA_TYPE'] != 'text')
  263. {
  264. //主键
  265. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined)
  266. {
  267. $priDefined = TRUE;
  268. $javascriptList[] = "{field: 'state', checkbox: true}";
  269. }
  270. //构造JS列信息
  271. $javascriptList[] = $this->getJsColumn($field);
  272. //排序方式,如果有weigh则按weigh,否则按主键排序
  273. $order = $field == 'weigh' ? 'weigh' : $order;
  274. }
  275. }
  276. //JS最后一列加上操作列
  277. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  278. $addList = implode("\n", array_filter($addList));
  279. $editList = implode("\n", array_filter($editList));
  280. $javascriptList = implode(",\n", array_filter($javascriptList));
  281. $langList = implode(",\n", array_filter($langList));
  282. //表注释
  283. $tableComment = $tableInfo['Comment'];
  284. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  285. //最终将生成的文件路径
  286. $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
  287. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
  288. $addFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'add.html';
  289. $editFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'edit.html';
  290. $indexFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'index.html';
  291. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
  292. $appNamespace = Config::get('app_namespace');
  293. $moduleName = 'admin';
  294. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  295. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  296. $data = [
  297. 'controllerNamespace' => $controllerNamespace,
  298. 'modelNamespace' => $modelNamespace,
  299. 'controllerUrl' => $controllerUrl,
  300. 'controllerDir' => $controllerDir,
  301. 'controllerName' => $controllerName,
  302. 'modelName' => $modelName,
  303. 'tableComment' => $tableComment,
  304. 'iconName' => $iconName,
  305. 'order' => $order,
  306. 'table' => $table,
  307. 'tableName' => $tableName,
  308. 'addList' => $addList,
  309. 'editList' => $editList,
  310. 'javascriptList' => $javascriptList,
  311. 'langList' => $langList,
  312. 'modelAutoWriteTimestamp' => in_array('createtime', $fields) || in_array('updatetime', $fields) ? "'int'" : 'false',
  313. 'createTime' => in_array('createtime', $fields) ? "'createtime'" : 'false',
  314. 'updateTime' => in_array('updatetime', $fields) ? "'updatetime'" : 'false',
  315. ];
  316. // 生成控制器文件
  317. $result = $this->writeToFile('controller', $data, $controllerFile);
  318. // 生成模型文件
  319. $result = $this->writeToFile('model', $data, $modelFile);
  320. // 生成视图文件
  321. $result = $this->writeToFile('add', $data, $addFile);
  322. $result = $this->writeToFile('edit', $data, $editFile);
  323. $result = $this->writeToFile('index', $data, $indexFile);
  324. // 生成JS文件
  325. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  326. // 生成语言文件
  327. if ($langList)
  328. {
  329. $result = $this->writeToFile('lang', $data, $langFile);
  330. }
  331. }
  332. catch (\think\exception\ErrorException $e)
  333. {
  334. print_r($e);
  335. }
  336. $output->writeln("<info>Build Successed</info>");
  337. }
  338. /**
  339. * 写入到文件
  340. * @param string $name
  341. * @param array $data
  342. * @param string $pathname
  343. * @return mixed
  344. */
  345. protected function writeToFile($name, $data, $pathname)
  346. {
  347. $search = $replace = [];
  348. foreach ($data as $k => $v)
  349. {
  350. $search[] = "{%{$k}%}";
  351. $replace[] = $v;
  352. }
  353. $stub = file_get_contents($this->getStub($name));
  354. $content = str_replace($search, $replace, $stub);
  355. if (!is_dir(dirname($pathname)))
  356. {
  357. mkdir(strtolower(dirname($pathname)), 0755, true);
  358. }
  359. return file_put_contents($pathname, $content);
  360. }
  361. /**
  362. * 获取基础模板
  363. * @param string $name
  364. * @return string
  365. */
  366. protected function getStub($name)
  367. {
  368. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  369. }
  370. protected function getLangItem($field, $content)
  371. {
  372. if (!Lang::has($field))
  373. {
  374. return <<<EOD
  375. '{$field}' => '{$content}'
  376. EOD;
  377. }
  378. else
  379. {
  380. return '';
  381. }
  382. }
  383. /**
  384. * 读取数据和语言数组列表
  385. * @param array $arr
  386. * @return array
  387. */
  388. protected function getLangArray($arr, $withTpl = TRUE)
  389. {
  390. $langArr = [];
  391. foreach ($arr as $k => $v)
  392. {
  393. $langArr[(is_numeric($k) ? $v : $k)] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  394. }
  395. return $langArr;
  396. }
  397. /**
  398. * 将数据转换成带字符串
  399. * @param array $arr
  400. * @return string
  401. */
  402. protected function getArrayString($arr)
  403. {
  404. $stringArr = [];
  405. foreach ($arr as $k => $v)
  406. {
  407. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  408. if (!$is_var)
  409. {
  410. $v = str_replace("'", "\'", $v);
  411. $k = str_replace("'", "\'", $k);
  412. }
  413. $stringArr[] = "'" . (is_numeric($k) ? $v : $k) . "' => " . (is_numeric($k) ? "__('" . ucfirst($k) . "')" : $is_var ? $v : "'{$v}'");
  414. }
  415. return implode(",", $stringArr);
  416. }
  417. protected function getFieldType(& $v)
  418. {
  419. $inputType = 'text';
  420. switch ($v['DATA_TYPE'])
  421. {
  422. case 'bigint':
  423. case 'int':
  424. case 'mediumint':
  425. case 'smallint':
  426. case 'tinyint':
  427. $inputType = 'number';
  428. break;
  429. case 'enum':
  430. case 'set':
  431. $inputType = 'select';
  432. break;
  433. case 'decimal':
  434. case 'double':
  435. case 'float':
  436. $inputType = 'number';
  437. break;
  438. case 'longtext':
  439. case 'text':
  440. case 'mediumtext':
  441. case 'smalltext':
  442. case 'tinytext':
  443. $inputType = 'textarea';
  444. break;
  445. case 'year';
  446. case 'date';
  447. case 'time';
  448. case 'datetime';
  449. case 'timestamp';
  450. $inputType = 'datetime';
  451. break;
  452. default:
  453. break;
  454. }
  455. $fieldsName = $v['COLUMN_NAME'];
  456. // 如果后缀以time结尾说明也是个时间字段
  457. if (substr($fieldsName, -4) == 'time')
  458. {
  459. $inputType = 'datetime';
  460. }
  461. // 如果后缀以data结尾且类型为enum,说明是个单选框
  462. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'enum')
  463. {
  464. $inputType = "radio";
  465. }
  466. // 如果后缀以data结尾且类型为set,说明是个复选框
  467. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'set')
  468. {
  469. $inputType = "checkbox";
  470. }
  471. return $inputType;
  472. }
  473. /**
  474. * 获取表单分组数据
  475. * @param string $field
  476. * @param string $content
  477. * @return string
  478. */
  479. protected function getFormGroup($field, $content)
  480. {
  481. $langField = ucfirst($field);
  482. return<<<EOD
  483. <div class="form-group">
  484. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  485. <div class="col-xs-12 col-sm-8">
  486. {$content}
  487. </div>
  488. </div>
  489. EOD;
  490. }
  491. /**
  492. * 获取图片模板数据
  493. * @param string $field
  494. * @param string $content
  495. * @return array
  496. */
  497. protected function getImageUpload($field, $content)
  498. {
  499. $filter = substr($field, -4) == 'avatar' || substr($field, -5) == 'image' ? 'data-mimetype="image/*"' : "";
  500. return <<<EOD
  501. <div class="form-inline">
  502. {$content}
  503. <span><button id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$filter}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  504. </div>
  505. EOD;
  506. }
  507. /**
  508. * 获取JS列数据
  509. * @param string $field
  510. * @return string
  511. */
  512. protected function getJsColumn($field)
  513. {
  514. $lang = ucfirst($field);
  515. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  516. $formatter = '';
  517. if ($field == 'status')
  518. $formatter = 'status';
  519. else if ($field == 'icon')
  520. $formatter = 'icon';
  521. else if ($field == 'flag')
  522. $formatter = 'flag';
  523. else if (substr($field, -4) == 'time')
  524. $formatter = 'datetime';
  525. else if (substr($field, -3) == 'url')
  526. $formatter = 'url';
  527. else if (substr($field, -5) == 'image')
  528. $formatter = 'image';
  529. if ($formatter)
  530. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  531. else
  532. $html .= "}";
  533. return $html;
  534. }
  535. }