Crud.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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 $stubList = [];
  15. protected function configure()
  16. {
  17. $this
  18. ->setName('crud')
  19. ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
  20. ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
  21. ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
  22. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
  23. ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
  24. ->addOption('relation', 'r', Option::VALUE_OPTIONAL, 'relation table name without prefix', null)
  25. ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL, 'relation model name', null)
  26. ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL, 'relation foreign key', null)
  27. ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL, 'relation primary key', null)
  28. ->addOption('mode', 'o', Option::VALUE_OPTIONAL, 'relation table mode,hasone or belongsto', 'belongsto')
  29. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
  30. ->setDescription('Build CRUD controller and model from table');
  31. }
  32. protected function execute(Input $input, Output $output)
  33. {
  34. $adminPath = dirname(__DIR__) . DS;
  35. //表名
  36. $table = $input->getOption('table') ?: '';
  37. //自定义控制器
  38. $controller = $input->getOption('controller');
  39. //自定义模型
  40. $model = $input->getOption('model');
  41. //强制覆盖
  42. $force = $input->getOption('force');
  43. //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
  44. $local = $input->getOption('local');
  45. if (!$table)
  46. {
  47. throw new Exception('table name can\'t empty');
  48. }
  49. //关联表
  50. $relation = $input->getOption('relation');
  51. //自定义关联表模型
  52. $relationModel = $input->getOption('relationmodel');
  53. //模式
  54. $mode = $input->getOption('mode');
  55. //外键
  56. $relationForeignKey = $input->getOption('relationforeignkey');
  57. //主键
  58. $relationPrimaryKey = $input->getOption('relationprimarykey');
  59. //如果有启用关联模式
  60. if ($relation && !in_array($mode, ['hasone', 'belongsto']))
  61. {
  62. throw new Exception("relation table only work in hasone or belongsto mode");
  63. }
  64. $dbname = Config::get('database.database');
  65. $prefix = Config::get('database.prefix');
  66. //检查主表
  67. $tableName = $prefix . $table;
  68. $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
  69. if (!$tableInfo)
  70. {
  71. throw new Exception("table not found");
  72. }
  73. $tableInfo = $tableInfo[0];
  74. //检查关联表
  75. if ($relation)
  76. {
  77. $relationTableName = $prefix . $relation;
  78. $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE);
  79. if (!$relationTableInfo)
  80. {
  81. throw new Exception("relation table not found");
  82. }
  83. }
  84. //根据表名匹配对应的Fontawesome图标
  85. $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
  86. $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? $table : 'fa fa-circle-o';
  87. //控制器默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入controller,格式为目录层级
  88. $controllerArr = !$controller ? explode('_', strtolower($table)) : explode('/', strtolower($controller));
  89. $controllerUrl = implode('/', $controllerArr);
  90. $controllerName = ucfirst(array_pop($controllerArr));
  91. $controllerDir = implode(DS, $controllerArr);
  92. $controllerFile = ($controllerDir ? $controllerDir . DS : '') . $controllerName . '.php';
  93. $viewDir = $adminPath . 'view' . DS . $controllerUrl . DS;
  94. //最终将生成的文件路径
  95. $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
  96. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
  97. $addFile = $viewDir . 'add.html';
  98. $editFile = $viewDir . 'edit.html';
  99. $indexFile = $viewDir . 'index.html';
  100. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
  101. //模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入model,不支持目录层级
  102. $modelName = $this->getModelName($model, $table);
  103. $modelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $modelName . '.php';
  104. $validateFile = $adminPath . 'validate' . DS . $modelName . '.php';
  105. //关联模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入relationmodel,不支持目录层级
  106. $relationModelName = $this->getModelName($relationModel, $relation);
  107. $relationModelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $relationModelName . '.php';
  108. //是否为删除模式
  109. $delete = $input->getOption('delete');
  110. if ($delete)
  111. {
  112. $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $langFile, $javascriptFile];
  113. foreach ($readyFiles as $k => $v)
  114. {
  115. $output->warning($v);
  116. }
  117. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  118. $line = fgets(STDIN);
  119. if (trim($line) != 'yes')
  120. {
  121. throw new Exception("Operation is aborted!");
  122. }
  123. foreach ($readyFiles as $k => $v)
  124. {
  125. unlink($v);
  126. }
  127. $output->info("Delete Successed");
  128. return;
  129. }
  130. //非覆盖模式时如果存在控制器文件则报错
  131. if (is_file($controllerFile) && !$force)
  132. {
  133. throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  134. }
  135. //非覆盖模式时如果存在模型文件则报错
  136. if (is_file($modelFile) && !$force)
  137. {
  138. throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  139. }
  140. //非覆盖模式时如果存在验证文件则报错
  141. if (is_file($validateFile) && !$force)
  142. {
  143. throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  144. }
  145. require $adminPath . 'common.php';
  146. //从数据库中获取表字段信息
  147. $sql = "SELECT * FROM `information_schema`.`columns` "
  148. . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  149. . "ORDER BY ORDINAL_POSITION";
  150. $columnList = Db::query($sql, [$dbname, $tableName]);
  151. $relationColumnList = [];
  152. if ($relation)
  153. {
  154. $relationColumnList = Db::query($sql, [$dbname, $relationTableName]);
  155. }
  156. $fieldArr = [];
  157. foreach ($columnList as $k => $v)
  158. {
  159. $fieldArr[] = $v['COLUMN_NAME'];
  160. }
  161. $relationFieldArr = [];
  162. foreach ($relationColumnList as $k => $v)
  163. {
  164. $relationFieldArr[] = $v['COLUMN_NAME'];
  165. }
  166. $addList = [];
  167. $editList = [];
  168. $javascriptList = [];
  169. $langList = [];
  170. $field = 'id';
  171. $order = 'id';
  172. $priDefined = FALSE;
  173. $priKey = '';
  174. $relationPriKey = '';
  175. foreach ($columnList as $k => $v)
  176. {
  177. if ($v['COLUMN_KEY'] == 'PRI')
  178. {
  179. $priKey = $v['COLUMN_NAME'];
  180. break;
  181. }
  182. }
  183. if (!$priKey)
  184. {
  185. throw new Exception('Primary key not found!');
  186. }
  187. if ($relation)
  188. {
  189. foreach ($relationColumnList as $k => $v)
  190. {
  191. if ($v['COLUMN_KEY'] == 'PRI')
  192. {
  193. $relationPriKey = $v['COLUMN_NAME'];
  194. break;
  195. }
  196. }
  197. if (!$relationPriKey)
  198. {
  199. throw new Exception('Relation Primary key not found!');
  200. }
  201. }
  202. $order = $priKey;
  203. //如果是关联模型
  204. if ($relation)
  205. {
  206. if ($mode == 'hasone')
  207. {
  208. $relationForeignKey = $relationForeignKey ? $relationForeignKey : $table . "_id";
  209. $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
  210. if (!in_array($relationForeignKey, $relationFieldArr))
  211. {
  212. throw new Exception('relation table must be contain field:' . $relationForeignKey);
  213. }
  214. if (!in_array($relationPrimaryKey, $fieldArr))
  215. {
  216. throw new Exception('table must be contain field:' . $relationPrimaryKey);
  217. }
  218. }
  219. else
  220. {
  221. $relationForeignKey = $relationForeignKey ? $relationForeignKey : $relation . "_id";
  222. $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $relationPriKey;
  223. if (!in_array($relationForeignKey, $fieldArr))
  224. {
  225. throw new Exception('table must be contain field:' . $relationForeignKey);
  226. }
  227. if (!in_array($relationPrimaryKey, $relationFieldArr))
  228. {
  229. throw new Exception('relation table must be contain field:' . $relationPrimaryKey);
  230. }
  231. }
  232. }
  233. try
  234. {
  235. Form::setEscapeHtml(false);
  236. $setAttrArr = [];
  237. $getAttrArr = [];
  238. $getEnumArr = [];
  239. $appendAttrList = [];
  240. $controllerAssignList = [];
  241. //循环所有字段,开始构造视图的HTML和JS信息
  242. foreach ($columnList as $k => $v)
  243. {
  244. $field = $v['COLUMN_NAME'];
  245. $itemArr = [];
  246. // 这里构建Enum和Set类型的列表数据
  247. if (in_array($v['DATA_TYPE'], ['enum', 'set']))
  248. {
  249. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  250. $itemArr = explode(',', str_replace("'", '', $itemArr));
  251. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  252. }
  253. // 语言列表
  254. if ($v['COLUMN_COMMENT'] != '')
  255. {
  256. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  257. }
  258. $inputType = '';
  259. //createtime和updatetime是保留字段不能修改和添加
  260. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, ['createtime', 'updatetime']))
  261. {
  262. $inputType = $this->getFieldType($v);
  263. // 如果是number类型时增加一个步长
  264. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  265. $attrArr = ['id' => "c-{$field}"];
  266. $cssClassArr = ['form-control'];
  267. $fieldName = "row[{$field}]";
  268. $defaultValue = $v['COLUMN_DEFAULT'];
  269. $editValue = "{\$row.{$field}}";
  270. // 如果默认值为空,则是一个必选项
  271. if ($v['COLUMN_DEFAULT'] == '')
  272. {
  273. $attrArr['data-rule'] = 'required';
  274. }
  275. if ($inputType == 'select')
  276. {
  277. $cssClassArr[] = 'selectpicker';
  278. $attrArr['class'] = implode(' ', $cssClassArr);
  279. if ($v['DATA_TYPE'] == 'set')
  280. {
  281. $attrArr['multiple'] = '';
  282. $fieldName .= "[]";
  283. }
  284. $attrArr['name'] = $fieldName;
  285. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  286. $itemArr = $this->getLangArray($itemArr, FALSE);
  287. //添加一个获取器
  288. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  289. $this->appendAttr($appendAttrList, $field);
  290. $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  291. $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  292. }
  293. else if ($inputType == 'datetime')
  294. {
  295. $cssClassArr[] = 'datetimepicker';
  296. $attrArr['class'] = implode(' ', $cssClassArr);
  297. $format = "YYYY-MM-DD HH:mm:ss";
  298. $phpFormat = "Y-m-d H:i:s";
  299. $fieldFunc = '';
  300. switch ($v['DATA_TYPE'])
  301. {
  302. case 'year';
  303. $format = "YYYY";
  304. $phpFormat = 'Y';
  305. break;
  306. case 'date';
  307. $format = "YYYY-MM-DD";
  308. $phpFormat = 'Y-m-d';
  309. break;
  310. case 'time';
  311. $format = "HH:mm:ss";
  312. $phpFormat = 'H:i:s';
  313. break;
  314. case 'timestamp';
  315. $fieldFunc = 'datetime';
  316. case 'datetime';
  317. $format = "YYYY-MM-DD HH:mm:ss";
  318. $phpFormat = 'Y-m-d H:i:s';
  319. break;
  320. default:
  321. $fieldFunc = 'datetime';
  322. $this->getAttr($getAttrArr, $field, $inputType);
  323. $this->setAttr($setAttrArr, $field, $inputType);
  324. $this->appendAttr($appendAttrList, $field);
  325. break;
  326. }
  327. $defaultDateTime = "{:date('{$phpFormat}')}";
  328. $attrArr['data-date-format'] = $format;
  329. $attrArr['data-use-current'] = "true";
  330. $fieldFunc = $fieldFunc ? "|{$fieldFunc}" : "";
  331. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  332. $formEditElement = Form::text($fieldName, "{\$row.{$field}{$fieldFunc}}", $attrArr);
  333. }
  334. else if ($inputType == 'checkbox' || $inputType == 'radio')
  335. {
  336. $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
  337. $attrArr['name'] = "row[{$fieldName}]";
  338. $itemArr = $this->getLangArray($itemArr, FALSE);
  339. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
  340. //添加一个获取器
  341. $this->getAttr($getAttrArr, $field, $inputType);
  342. $this->appendAttr($appendAttrList, $field);
  343. $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
  344. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  345. $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  346. }
  347. else if ($inputType == 'textarea')
  348. {
  349. $cssClassArr[] = substr($field, -7) == 'content' ? 'summernote' : '';
  350. $attrArr['class'] = implode(' ', $cssClassArr);
  351. $attrArr['rows'] = 5;
  352. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  353. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  354. }
  355. else if ($field == 'category_id' || $field == 'category_ids')
  356. {
  357. $type = $table;
  358. if ($field == 'category_ids')
  359. {
  360. $attrArr['multiple'] = '';
  361. }
  362. $attrStr = $this->getArrayString($attrArr);
  363. $formAddElement = "{:build_category_select('{$fieldName}', '{$type}', '{$defaultValue}', [{$attrStr}])}";
  364. $formEditElement = "{:build_category_select('{$fieldName}', '{$type}', \$row.{$field}, [{$attrStr}])}";
  365. }
  366. else
  367. {
  368. //CSS类名
  369. $cssClassArr[] = substr($field, -3) == '_id' ? 'typeahead' : '';
  370. $cssClassArr[] = substr($field, -4) == '_ids' ? 'tagsinput' : '';
  371. $cssClassArr = array_filter($cssClassArr);
  372. //因为有自动完成可输入其它内容
  373. $step = array_intersect($cssClassArr, ['typeahead', 'tagsinput']) ? 0 : $step;
  374. $attrArr['class'] = implode(' ', $cssClassArr);
  375. $isUpload = in_array(substr($field, -4), ['file']) || in_array(substr($field, -5), ['files', 'image']) || in_array(substr($field, -6), ['images', 'avatar']) || in_array(substr($field, -7), ['avatars']) ? TRUE : FALSE;
  376. //如果是步长则加上步长
  377. if ($step)
  378. {
  379. $attrArr['step'] = $step;
  380. }
  381. //如果是图片加上个size
  382. if ($isUpload)
  383. {
  384. $attrArr['size'] = 50;
  385. }
  386. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  387. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  388. //如果是图片或文件
  389. if ($isUpload)
  390. {
  391. $formAddElement = $this->getImageUpload($field, $formAddElement);
  392. $formEditElement = $this->getImageUpload($field, $formEditElement);
  393. }
  394. }
  395. //构造添加和编辑HTML信息
  396. $addList[] = $this->getFormGroup($field, $formAddElement);
  397. $editList[] = $this->getFormGroup($field, $formEditElement);
  398. }
  399. //过滤text类型字段
  400. if ($v['DATA_TYPE'] != 'text')
  401. {
  402. //主键
  403. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined)
  404. {
  405. $priDefined = TRUE;
  406. $javascriptList[] = "{field: 'state', checkbox: true}";
  407. }
  408. //构造JS列信息
  409. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE']);
  410. if ($inputType && in_array($inputType, ['select', 'checkbox', 'radio']))
  411. {
  412. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], '_text');
  413. }
  414. //排序方式,如果有weigh则按weigh,否则按主键排序
  415. $order = $field == 'weigh' ? 'weigh' : $order;
  416. }
  417. }
  418. $relationPriKey = 'id';
  419. $relationFieldArr = [];
  420. foreach ($relationColumnList as $k => $v)
  421. {
  422. $relationField = $v['COLUMN_NAME'];
  423. $relationFieldArr[] = $field;
  424. $relationField = strtolower($relationModelName) . "." . $relationField;
  425. // 语言列表
  426. if ($v['COLUMN_COMMENT'] != '')
  427. {
  428. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  429. }
  430. //过滤text类型字段
  431. if ($v['DATA_TYPE'] != 'text')
  432. {
  433. //构造JS列信息
  434. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  435. }
  436. }
  437. //JS最后一列加上操作列
  438. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  439. $addList = implode("\n", array_filter($addList));
  440. $editList = implode("\n", array_filter($editList));
  441. $javascriptList = implode(",\n", array_filter($javascriptList));
  442. $langList = implode(",\n", array_filter($langList));
  443. //表注释
  444. $tableComment = $tableInfo['Comment'];
  445. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  446. $appNamespace = Config::get('app_namespace');
  447. $moduleName = 'admin';
  448. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  449. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  450. $validateNamespace = "{$appNamespace}\\" . $moduleName . "\\validate";
  451. $validateName = $modelName;
  452. $data = [
  453. 'controllerNamespace' => $controllerNamespace,
  454. 'modelNamespace' => $modelNamespace,
  455. 'validateNamespace' => $validateNamespace,
  456. 'controllerUrl' => $controllerUrl,
  457. 'controllerDir' => $controllerDir,
  458. 'controllerName' => $controllerName,
  459. 'controllerAssignList' => implode("\n", $controllerAssignList),
  460. 'modelName' => $modelName,
  461. 'validateName' => $validateName,
  462. 'tableComment' => $tableComment,
  463. 'iconName' => $iconName,
  464. 'pk' => $priKey,
  465. 'order' => $order,
  466. 'table' => $table,
  467. 'tableName' => $tableName,
  468. 'addList' => $addList,
  469. 'editList' => $editList,
  470. 'javascriptList' => $javascriptList,
  471. 'langList' => $langList,
  472. 'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
  473. 'createTime' => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
  474. 'updateTime' => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
  475. 'modelTableName' => $table,
  476. 'relationModelTableName' => $relation,
  477. 'relationModelName' => $relationModelName,
  478. 'relationWith' => '',
  479. 'relationMethod' => '',
  480. 'relationModel' => '',
  481. 'relationForeignKey' => '',
  482. 'relationPrimaryKey' => '',
  483. 'relationSearch' => $relation ? 'true' : 'false',
  484. 'controllerIndex' => '',
  485. 'appendAttrList' => implode(",\n", $appendAttrList),
  486. 'getEnumList' => implode("\n\n", $getEnumArr),
  487. 'getAttrList' => implode("\n\n", $getAttrArr),
  488. 'setAttrList' => implode("\n\n", $setAttrArr),
  489. 'modelMethod' => '',
  490. ];
  491. //如果使用关联模型
  492. if ($relation)
  493. {
  494. //需要构造关联的方法
  495. $data['relationMethod'] = strtolower($relationModelName);
  496. //预载入的方法
  497. $data['relationWith'] = "->with('{$data['relationMethod']}')";
  498. //需要重写index方法
  499. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  500. //关联的模式
  501. $data['relationMode'] = $mode == 'hasone' ? 'hasOne' : 'belongsTo';
  502. //关联字段
  503. $data['relationForeignKey'] = $relationForeignKey;
  504. $data['relationPrimaryKey'] = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
  505. //构造关联模型的方法
  506. $data['modelMethod'] = $this->getReplacedStub('modelmethod', $data);
  507. }
  508. // 生成控制器文件
  509. $result = $this->writeToFile('controller', $data, $controllerFile);
  510. // 生成模型文件
  511. $result = $this->writeToFile('model', $data, $modelFile);
  512. if ($relation && !is_file($relationModelFile))
  513. {
  514. // 生成关联模型文件
  515. $result = $this->writeToFile('relationmodel', $data, $relationModelFile);
  516. }
  517. // 生成验证文件
  518. $result = $this->writeToFile('validate', $data, $validateFile);
  519. // 生成视图文件
  520. $result = $this->writeToFile('add', $data, $addFile);
  521. $result = $this->writeToFile('edit', $data, $editFile);
  522. $result = $this->writeToFile('index', $data, $indexFile);
  523. // 生成JS文件
  524. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  525. // 生成语言文件
  526. if ($langList)
  527. {
  528. $result = $this->writeToFile('lang', $data, $langFile);
  529. }
  530. }
  531. catch (\think\exception\ErrorException $e)
  532. {
  533. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage());
  534. }
  535. $output->info("Build Successed");
  536. }
  537. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  538. {
  539. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  540. return;
  541. $fieldList = $this->getFieldListName($field);
  542. $methodName = 'get' . ucfirst($fieldList);
  543. unset($v);
  544. foreach ($itemArr as $k => &$v)
  545. {
  546. $v = "__('" . ucfirst($v) . "')";
  547. }
  548. unset($v);
  549. $itemString = $this->getArrayString($itemArr);
  550. $getEnum[] = <<<EOD
  551. public function {$methodName}()
  552. {
  553. return [{$itemString}];
  554. }
  555. EOD;
  556. $controllerAssignList[] = <<<EOD
  557. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  558. EOD;
  559. }
  560. protected function getAttr(&$getAttr, $field, $inputType = '')
  561. {
  562. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  563. return;
  564. $attrField = ucfirst($this->getCamelizeName($field));
  565. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  566. }
  567. protected function setAttr(&$setAttr, $field, $inputType = '')
  568. {
  569. if ($inputType != 'datetime')
  570. return;
  571. $attrField = ucfirst($this->getCamelizeName($field));
  572. if ($inputType == 'datetime')
  573. {
  574. $return = <<<EOD
  575. return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
  576. EOD;
  577. }
  578. $setAttr[] = <<<EOD
  579. protected function set{$attrField}Attr(\$value)
  580. {
  581. $return
  582. }
  583. EOD;
  584. }
  585. protected function appendAttr(&$appendAttrList, $field)
  586. {
  587. $appendAttrList[] = <<<EOD
  588. '{$field}_text'
  589. EOD;
  590. }
  591. protected function getModelName($model, $table)
  592. {
  593. if (!$model)
  594. {
  595. $modelarr = explode('_', strtolower($table));
  596. foreach ($modelarr as $k => &$v)
  597. $v = ucfirst($v);
  598. unset($v);
  599. $modelName = implode('', $modelarr);
  600. }
  601. else
  602. {
  603. $modelName = ucfirst($model);
  604. }
  605. return $modelName;
  606. }
  607. /**
  608. * 写入到文件
  609. * @param string $name
  610. * @param array $data
  611. * @param string $pathname
  612. * @return mixed
  613. */
  614. protected function writeToFile($name, $data, $pathname)
  615. {
  616. $content = $this->getReplacedStub($name, $data);
  617. if (!is_dir(dirname($pathname)))
  618. {
  619. mkdir(strtolower(dirname($pathname)), 0755, true);
  620. }
  621. return file_put_contents($pathname, $content);
  622. }
  623. /**
  624. * 获取替换后的数据
  625. * @param string $name
  626. * @param array $data
  627. * @return string
  628. */
  629. protected function getReplacedStub($name, $data)
  630. {
  631. $search = $replace = [];
  632. foreach ($data as $k => $v)
  633. {
  634. $search[] = "{%{$k}%}";
  635. $replace[] = $v;
  636. }
  637. $stubname = $this->getStub($name);
  638. if (isset($this->stubList[$stubname]))
  639. {
  640. $stub = $this->stubList[$stubname];
  641. }
  642. else
  643. {
  644. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  645. }
  646. $content = str_replace($search, $replace, $stub);
  647. return $content;
  648. }
  649. /**
  650. * 获取基础模板
  651. * @param string $name
  652. * @return string
  653. */
  654. protected function getStub($name)
  655. {
  656. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  657. }
  658. protected function getLangItem($field, $content)
  659. {
  660. if ($content || !Lang::has($field))
  661. {
  662. $itemArr = [];
  663. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false)
  664. {
  665. list($fieldLang, $item) = explode(':', $content);
  666. $itemArr = [$field => $fieldLang];
  667. foreach (explode(',', $item) as $k => $v)
  668. {
  669. list($key, $value) = explode('=', $v);
  670. $itemArr[$field . ' ' . $key] = $value;
  671. }
  672. }
  673. else
  674. {
  675. $itemArr = [$field => $content];
  676. }
  677. $resultArr = [];
  678. foreach ($itemArr as $k => $v)
  679. {
  680. $resultArr[] = " '" . ucfirst($k) . "' => '{$v}'";
  681. }
  682. return implode(",\n", $resultArr);
  683. }
  684. else
  685. {
  686. return '';
  687. }
  688. }
  689. /**
  690. * 读取数据和语言数组列表
  691. * @param array $arr
  692. * @return array
  693. */
  694. protected function getLangArray($arr, $withTpl = TRUE)
  695. {
  696. $langArr = [];
  697. foreach ($arr as $k => $v)
  698. {
  699. $langArr[(is_numeric($k) ? $v : $k)] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  700. }
  701. return $langArr;
  702. }
  703. /**
  704. * 将数据转换成带字符串
  705. * @param array $arr
  706. * @return string
  707. */
  708. protected function getArrayString($arr)
  709. {
  710. if (!is_array($arr))
  711. return $arr;
  712. $stringArr = [];
  713. foreach ($arr as $k => $v)
  714. {
  715. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  716. if (!$is_var)
  717. {
  718. $v = str_replace("'", "\'", $v);
  719. $k = str_replace("'", "\'", $k);
  720. }
  721. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  722. }
  723. return implode(",", $stringArr);
  724. }
  725. protected function getItemArray($item, $field, $comment)
  726. {
  727. $itemArr = [];
  728. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false)
  729. {
  730. list($fieldLang, $item) = explode(':', $comment);
  731. $itemArr = [];
  732. foreach (explode(',', $item) as $k => $v)
  733. {
  734. list($key, $value) = explode('=', $v);
  735. $itemArr[$key] = $field . ' ' . $key;
  736. }
  737. }
  738. else
  739. {
  740. foreach ($item as $k => $v)
  741. {
  742. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  743. }
  744. }
  745. return $itemArr;
  746. }
  747. protected function getFieldType(& $v)
  748. {
  749. $inputType = 'text';
  750. switch ($v['DATA_TYPE'])
  751. {
  752. case 'bigint':
  753. case 'int':
  754. case 'mediumint':
  755. case 'smallint':
  756. case 'tinyint':
  757. $inputType = 'number';
  758. break;
  759. case 'enum':
  760. case 'set':
  761. $inputType = 'select';
  762. break;
  763. case 'decimal':
  764. case 'double':
  765. case 'float':
  766. $inputType = 'number';
  767. break;
  768. case 'longtext':
  769. case 'text':
  770. case 'mediumtext':
  771. case 'smalltext':
  772. case 'tinytext':
  773. $inputType = 'textarea';
  774. break;
  775. case 'year';
  776. case 'date';
  777. case 'time';
  778. case 'datetime';
  779. case 'timestamp';
  780. $inputType = 'datetime';
  781. break;
  782. default:
  783. break;
  784. }
  785. $fieldsName = $v['COLUMN_NAME'];
  786. // 如果后缀以time结尾说明也是个时间字段
  787. if (substr($fieldsName, -4) == 'time')
  788. {
  789. $inputType = 'datetime';
  790. }
  791. // 如果后缀以data结尾且类型为enum,说明是个单选框
  792. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'enum')
  793. {
  794. $inputType = "radio";
  795. }
  796. // 如果后缀以data结尾且类型为set,说明是个复选框
  797. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'set')
  798. {
  799. $inputType = "checkbox";
  800. }
  801. return $inputType;
  802. }
  803. /**
  804. * 获取表单分组数据
  805. * @param string $field
  806. * @param string $content
  807. * @return string
  808. */
  809. protected function getFormGroup($field, $content)
  810. {
  811. $langField = ucfirst($field);
  812. return<<<EOD
  813. <div class="form-group">
  814. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  815. <div class="col-xs-12 col-sm-8">
  816. {$content}
  817. </div>
  818. </div>
  819. EOD;
  820. }
  821. /**
  822. * 获取图片模板数据
  823. * @param string $field
  824. * @param string $content
  825. * @return array
  826. */
  827. protected function getImageUpload($field, $content)
  828. {
  829. $filter = substr($field, -4) == 'avatar' || substr($field, -5) == 'image' || substr($field, -6) == 'images' ? ' data-mimetype="image/*"' : "";
  830. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  831. $preview = $filter ? ' data-preview-id="p-' . $field . '"' : '';
  832. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  833. return <<<EOD
  834. <div class="form-inline">
  835. {$content}
  836. <span><button type="button" id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$filter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  837. <span><button type="button" id="fachoose-{$field}" class="btn btn-primary fachoose" data-input-id="c-{$field}"{$filter}{$multiple}><i class="fa fa-list"></i> {:__('Choose')}</button></span>
  838. {$previewcontainer}
  839. </div>
  840. EOD;
  841. }
  842. /**
  843. * 获取JS列数据
  844. * @param string $field
  845. * @return string
  846. */
  847. protected function getJsColumn($field, $datatype = '', $extend = '')
  848. {
  849. $lang = ucfirst($field);
  850. $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
  851. $field = stripos($field, ".") !== false ? substr($field, stripos($field, '.') + 1) : $field;
  852. $formatter = '';
  853. if ($field == 'status')
  854. $formatter = 'status';
  855. else if ($field == 'icon')
  856. $formatter = 'icon';
  857. else if ($field == 'flag')
  858. $formatter = 'flag';
  859. else if (substr($field, -4) == 'time' && in_array($datatype, ['int', 'timestamp']))
  860. $formatter = 'datetime';
  861. else if (substr($field, -3) == 'url' || substr($field, -4) == 'file')
  862. $formatter = 'url';
  863. else if (substr($field, -5) == 'image')
  864. $formatter = 'image';
  865. else if (substr($field, -6) == 'images')
  866. $formatter = 'images';
  867. if ($extend)
  868. $html .= ", operate:false";
  869. if ($formatter && !$extend)
  870. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  871. else
  872. $html .= "}";
  873. return $html;
  874. }
  875. protected function getCamelizeName($uncamelized_words, $separator = '_')
  876. {
  877. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  878. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  879. }
  880. protected function getFieldListName($field)
  881. {
  882. return $this->getCamelizeName($field) . 'List';
  883. }
  884. }