Crud.php 43 KB

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