Crud.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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[] = "{field: 'state', 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. unset($v);
  651. foreach ($itemArr as $k => &$v)
  652. {
  653. $v = "__('" . ucfirst($v) . "')";
  654. }
  655. unset($v);
  656. $itemString = $this->getArrayString($itemArr);
  657. $getEnum[] = <<<EOD
  658. public function {$methodName}()
  659. {
  660. return [{$itemString}];
  661. }
  662. EOD;
  663. $controllerAssignList[] = <<<EOD
  664. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  665. EOD;
  666. }
  667. protected function getAttr(&$getAttr, $field, $inputType = '')
  668. {
  669. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  670. return;
  671. $attrField = ucfirst($this->getCamelizeName($field));
  672. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  673. }
  674. protected function setAttr(&$setAttr, $field, $inputType = '')
  675. {
  676. if ($inputType != 'datetime')
  677. return;
  678. $attrField = ucfirst($this->getCamelizeName($field));
  679. if ($inputType == 'datetime')
  680. {
  681. $return = <<<EOD
  682. return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
  683. EOD;
  684. }
  685. $setAttr[] = <<<EOD
  686. protected function set{$attrField}Attr(\$value)
  687. {
  688. $return
  689. }
  690. EOD;
  691. }
  692. protected function appendAttr(&$appendAttrList, $field)
  693. {
  694. $appendAttrList[] = <<<EOD
  695. '{$field}_text'
  696. EOD;
  697. }
  698. protected function getModelName($model, $table)
  699. {
  700. if (!$model)
  701. {
  702. $modelarr = explode('_', strtolower($table));
  703. foreach ($modelarr as $k => &$v)
  704. $v = ucfirst($v);
  705. unset($v);
  706. $modelName = implode('', $modelarr);
  707. }
  708. else
  709. {
  710. $modelName = ucfirst($model);
  711. }
  712. return $modelName;
  713. }
  714. /**
  715. * 写入到文件
  716. * @param string $name
  717. * @param array $data
  718. * @param string $pathname
  719. * @return mixed
  720. */
  721. protected function writeToFile($name, $data, $pathname)
  722. {
  723. $content = $this->getReplacedStub($name, $data);
  724. if (!is_dir(dirname($pathname)))
  725. {
  726. mkdir(strtolower(dirname($pathname)), 0755, true);
  727. }
  728. return file_put_contents($pathname, $content);
  729. }
  730. /**
  731. * 获取替换后的数据
  732. * @param string $name
  733. * @param array $data
  734. * @return string
  735. */
  736. protected function getReplacedStub($name, $data)
  737. {
  738. $search = $replace = [];
  739. foreach ($data as $k => $v)
  740. {
  741. $search[] = "{%{$k}%}";
  742. $replace[] = $v;
  743. }
  744. $stubname = $this->getStub($name);
  745. if (isset($this->stubList[$stubname]))
  746. {
  747. $stub = $this->stubList[$stubname];
  748. }
  749. else
  750. {
  751. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  752. }
  753. $content = str_replace($search, $replace, $stub);
  754. return $content;
  755. }
  756. /**
  757. * 获取基础模板
  758. * @param string $name
  759. * @return string
  760. */
  761. protected function getStub($name)
  762. {
  763. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  764. }
  765. protected function getLangItem($field, $content)
  766. {
  767. if ($content || !Lang::has($field))
  768. {
  769. $itemArr = [];
  770. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false)
  771. {
  772. list($fieldLang, $item) = explode(':', $content);
  773. $itemArr = [$field => $fieldLang];
  774. foreach (explode(',', $item) as $k => $v)
  775. {
  776. list($key, $value) = explode('=', $v);
  777. $itemArr[$field . ' ' . $key] = $value;
  778. }
  779. }
  780. else
  781. {
  782. $itemArr = [$field => $content];
  783. }
  784. $resultArr = [];
  785. foreach ($itemArr as $k => $v)
  786. {
  787. $resultArr[] = " '" . ucfirst($k) . "' => '{$v}'";
  788. }
  789. return implode(",\n", $resultArr);
  790. }
  791. else
  792. {
  793. return '';
  794. }
  795. }
  796. /**
  797. * 读取数据和语言数组列表
  798. * @param array $arr
  799. * @return array
  800. */
  801. protected function getLangArray($arr, $withTpl = TRUE)
  802. {
  803. $langArr = [];
  804. foreach ($arr as $k => $v)
  805. {
  806. $langArr[(is_numeric($k) ? $v : $k)] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  807. }
  808. return $langArr;
  809. }
  810. /**
  811. * 将数据转换成带字符串
  812. * @param array $arr
  813. * @return string
  814. */
  815. protected function getArrayString($arr)
  816. {
  817. if (!is_array($arr))
  818. return $arr;
  819. $stringArr = [];
  820. foreach ($arr as $k => $v)
  821. {
  822. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  823. if (!$is_var)
  824. {
  825. $v = str_replace("'", "\'", $v);
  826. $k = str_replace("'", "\'", $k);
  827. }
  828. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  829. }
  830. return implode(",", $stringArr);
  831. }
  832. protected function getItemArray($item, $field, $comment)
  833. {
  834. $itemArr = [];
  835. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false)
  836. {
  837. list($fieldLang, $item) = explode(':', $comment);
  838. $itemArr = [];
  839. foreach (explode(',', $item) as $k => $v)
  840. {
  841. list($key, $value) = explode('=', $v);
  842. $itemArr[$key] = $field . ' ' . $key;
  843. }
  844. }
  845. else
  846. {
  847. foreach ($item as $k => $v)
  848. {
  849. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  850. }
  851. }
  852. return $itemArr;
  853. }
  854. protected function getFieldType(& $v)
  855. {
  856. $inputType = 'text';
  857. switch ($v['DATA_TYPE'])
  858. {
  859. case 'bigint':
  860. case 'int':
  861. case 'mediumint':
  862. case 'smallint':
  863. case 'tinyint':
  864. $inputType = 'number';
  865. break;
  866. case 'enum':
  867. case 'set':
  868. $inputType = 'select';
  869. break;
  870. case 'decimal':
  871. case 'double':
  872. case 'float':
  873. $inputType = 'number';
  874. break;
  875. case 'longtext':
  876. case 'text':
  877. case 'mediumtext':
  878. case 'smalltext':
  879. case 'tinytext':
  880. $inputType = 'textarea';
  881. break;
  882. case 'year';
  883. case 'date';
  884. case 'time';
  885. case 'datetime';
  886. case 'timestamp';
  887. $inputType = 'datetime';
  888. break;
  889. default:
  890. break;
  891. }
  892. $fieldsName = $v['COLUMN_NAME'];
  893. // 指定后缀说明也是个时间字段
  894. if (preg_match("/{$this->intDateSuffix}$/i", $fieldsName))
  895. {
  896. $inputType = 'datetime';
  897. }
  898. // 指定后缀结尾且类型为enum,说明是个单选框
  899. if (preg_match("/{$this->enumRadioSuffix}$/i", $fieldsName) && $v['DATA_TYPE'] == 'enum')
  900. {
  901. $inputType = "radio";
  902. }
  903. // 指定后缀结尾且类型为set,说明是个复选框
  904. if (preg_match("/{$this->setCheckboxSuffix}$/i", $fieldsName) && $v['DATA_TYPE'] == 'set')
  905. {
  906. $inputType = "checkbox";
  907. }
  908. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  909. if (preg_match("/{$this->switchSuffix}$/i", $fieldsName) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null)
  910. {
  911. $inputType = "switch";
  912. }
  913. return $inputType;
  914. }
  915. /**
  916. * 获取表单分组数据
  917. * @param string $field
  918. * @param string $content
  919. * @return string
  920. */
  921. protected function getFormGroup($field, $content)
  922. {
  923. $langField = ucfirst($field);
  924. return<<<EOD
  925. <div class="form-group">
  926. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  927. <div class="col-xs-12 col-sm-8">
  928. {$content}
  929. </div>
  930. </div>
  931. EOD;
  932. }
  933. /**
  934. * 获取图片模板数据
  935. * @param string $field
  936. * @param string $content
  937. * @return array
  938. */
  939. protected function getImageUpload($field, $content)
  940. {
  941. $filter = '';
  942. foreach ($this->imageField as $k => $v)
  943. {
  944. if (preg_match("/{$v}$/i", $field))
  945. {
  946. $filter = ' data-mimetype="image/*"';
  947. break;
  948. }
  949. }
  950. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  951. $preview = $filter ? ' data-preview-id="p-' . $field . '"' : '';
  952. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  953. return <<<EOD
  954. <div class="form-inline">
  955. {$content}
  956. <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>
  957. <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>
  958. {$previewcontainer}
  959. </div>
  960. EOD;
  961. }
  962. /**
  963. * 获取JS列数据
  964. * @param string $field
  965. * @return string
  966. */
  967. protected function getJsColumn($field, $datatype = '', $extend = '')
  968. {
  969. $lang = ucfirst($field);
  970. $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
  971. $formatter = '';
  972. foreach ($this->fieldFormatterSuffix as $k => $v)
  973. {
  974. if (preg_match("/{$k}$/i", $field))
  975. {
  976. if (is_array($v))
  977. {
  978. if (in_array($datatype, $v['type']))
  979. {
  980. $formatter = $v['name'];
  981. break;
  982. }
  983. }
  984. else
  985. {
  986. $formatter = $v;
  987. break;
  988. }
  989. }
  990. }
  991. if ($extend)
  992. $html .= ", operate:false";
  993. if ($formatter && !$extend)
  994. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  995. else
  996. $html .= "}";
  997. return $html;
  998. }
  999. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1000. {
  1001. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1002. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1003. }
  1004. protected function getFieldListName($field)
  1005. {
  1006. return $this->getCamelizeName($field) . 'List';
  1007. }
  1008. }