Crud.php 34 KB

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