Crud.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. //循环所有字段,开始构造视图的HTML和JS信息
  199. foreach ($columnList as $k => $v)
  200. {
  201. $field = $v['COLUMN_NAME'];
  202. $itemArr = [];
  203. // 这里构建Enum和Set类型的列表数据
  204. if (in_array($v['DATA_TYPE'], ['enum', 'set']))
  205. {
  206. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  207. $itemArr = explode(',', str_replace("'", '', $itemArr));
  208. }
  209. // 语言列表
  210. if ($v['COLUMN_COMMENT'] != '')
  211. {
  212. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  213. }
  214. //createtime和updatetime是保留字段不能修改和添加
  215. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, ['createtime', 'updatetime']))
  216. {
  217. $inputType = $this->getFieldType($v);
  218. // 如果是number类型时增加一个步长
  219. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  220. $attrArr = ['id' => "c-{$field}"];
  221. $cssClassArr = ['form-control'];
  222. $fieldName = "row[{$field}]";
  223. $defaultValue = $v['COLUMN_DEFAULT'];
  224. $editValue = "{\$row.{$field}}";
  225. // 如果默认值为空,则是一个必选项
  226. if ($v['COLUMN_DEFAULT'] == '')
  227. {
  228. $attrArr['required'] = '';
  229. }
  230. if ($field == 'status' && in_array($inputType, ['text', 'number']))
  231. {
  232. //如果状态类型不是enum或set
  233. $itemArr = !$itemArr ? ['normal', 'hidden'] : $itemArr;
  234. $inputType = 'radio';
  235. }
  236. if ($inputType == 'select')
  237. {
  238. $cssClassArr[] = 'selectpicker';
  239. $attrArr['class'] = implode(' ', $cssClassArr);
  240. if ($v['DATA_TYPE'] == 'set')
  241. {
  242. $attrArr['multiple'] = '';
  243. $fieldName .= "[]";
  244. }
  245. $attrStr = $this->getArrayString($attrArr);
  246. $itemArr = $this->getLangArray($itemArr, FALSE);
  247. $itemString = $this->getArrayString($itemArr);
  248. $formAddElement = "{:build_select('{$fieldName}', [{$itemString}], '{$defaultValue}', [{$attrStr}])}";
  249. $formEditElement = "{:build_select('{$fieldName}', [{$itemString}], \$row.{$field}, [{$attrStr}])}";
  250. }
  251. else if ($inputType == 'datetime')
  252. {
  253. $cssClassArr[] = 'datetimepicker';
  254. $attrArr['class'] = implode(' ', $cssClassArr);
  255. $format = "YYYY-MM-DD HH:mm:ss";
  256. $phpFormat = "Y-m-d H:i:s";
  257. $fieldFunc = '';
  258. switch ($v['DATA_TYPE'])
  259. {
  260. case 'year';
  261. $format = "YYYY";
  262. $phpFormat = 'Y';
  263. break;
  264. case 'date';
  265. $format = "YYYY-MM-DD";
  266. $phpFormat = 'Y-m-d';
  267. break;
  268. case 'time';
  269. $format = "HH:mm:ss";
  270. $phpFormat = 'H:i:s';
  271. break;
  272. case 'timestamp';
  273. $fieldFunc = 'datetime';
  274. case 'datetime';
  275. $format = "YYYY-MM-DD HH:mm:ss";
  276. $phpFormat = 'Y-m-d H:i:s';
  277. break;
  278. default:
  279. $fieldFunc = 'datetime';
  280. break;
  281. }
  282. $defaultDateTime = "{:date('{$phpFormat}')}";
  283. $attrArr['data-date-format'] = $format;
  284. $attrArr['data-use-current'] = "true";
  285. $fieldFunc = $fieldFunc ? "|{$fieldFunc}" : "";
  286. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  287. $formEditElement = Form::text($fieldName, "{\$row.{$field}{$fieldFunc}}", $attrArr);
  288. }
  289. else if ($inputType == 'checkbox')
  290. {
  291. $fieldName .= "[]";
  292. $itemArr = $this->getLangArray($itemArr, FALSE);
  293. $itemString = $this->getArrayString($itemArr);
  294. $formAddElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
  295. $formEditElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], \$row.{$field})}";
  296. }
  297. else if ($inputType == 'radio')
  298. {
  299. $itemArr = $this->getLangArray($itemArr, FALSE);
  300. $itemString = $this->getArrayString($itemArr);
  301. $defaultValue = $defaultValue ? $defaultValue : key($itemArr);
  302. $formAddElement = "{:build_radios('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
  303. $formEditElement = "{:build_radios('{$fieldName}', [{$itemString}], \$row.{$field})}";
  304. }
  305. else if ($inputType == 'textarea')
  306. {
  307. $cssClassArr[] = substr($field, -7) == 'content' ? 'summernote' : '';
  308. $attrArr['class'] = implode(' ', $cssClassArr);
  309. $attrArr['rows'] = 5;
  310. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  311. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  312. }
  313. else if ($field == 'category_id' || $field == 'category_ids')
  314. {
  315. $type = $table;
  316. if ($field == 'category_ids')
  317. {
  318. $attrArr['multiple'] = '';
  319. }
  320. $attrStr = $this->getArrayString($attrArr);
  321. $formAddElement = "{:build_category_select('{$fieldName}', '{$type}', '{$defaultValue}', [{$attrStr}])}";
  322. $formEditElement = "{:build_category_select('{$fieldName}', '{$type}', \$row.{$field}, [{$attrStr}])}";
  323. }
  324. else
  325. {
  326. //CSS类名
  327. $cssClassArr[] = substr($field, -3) == '_id' ? 'typeahead' : '';
  328. $cssClassArr[] = substr($field, -4) == '_ids' ? 'tagsinput' : '';
  329. $cssClassArr = array_filter($cssClassArr);
  330. //因为有自动完成可输入其它内容
  331. $step = array_intersect($cssClassArr, ['typeahead', 'tagsinput']) ? 0 : $step;
  332. $attrArr['class'] = implode(' ', $cssClassArr);
  333. $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;
  334. //如果是步长则加上步长
  335. if ($step)
  336. {
  337. $attrArr['step'] = $step;
  338. }
  339. //如果是图片加上个size
  340. if ($isUpload)
  341. {
  342. $attrArr['size'] = 50;
  343. }
  344. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  345. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  346. //如果是图片或文件
  347. if ($isUpload)
  348. {
  349. $formAddElement = $this->getImageUpload($field, $formAddElement);
  350. $formEditElement = $this->getImageUpload($field, $formEditElement);
  351. }
  352. }
  353. //构造添加和编辑HTML信息
  354. $addList[] = $this->getFormGroup($field, $formAddElement);
  355. $editList[] = $this->getFormGroup($field, $formEditElement);
  356. }
  357. //过滤text类型字段
  358. if ($v['DATA_TYPE'] != 'text')
  359. {
  360. //主键
  361. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined)
  362. {
  363. $priDefined = TRUE;
  364. $javascriptList[] = "{field: 'state', checkbox: true}";
  365. }
  366. //构造JS列信息
  367. $javascriptList[] = $this->getJsColumn($field);
  368. //排序方式,如果有weigh则按weigh,否则按主键排序
  369. $order = $field == 'weigh' ? 'weigh' : $order;
  370. }
  371. }
  372. $relationPriKey = 'id';
  373. $relationFieldArr = [];
  374. foreach ($relationColumnList as $k => $v)
  375. {
  376. $relationField = $v['COLUMN_NAME'];
  377. $relationFieldArr[] = $field;
  378. $relationField = strtolower($relationModelName) . "." . $relationField;
  379. // 语言列表
  380. if ($v['COLUMN_COMMENT'] != '')
  381. {
  382. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  383. }
  384. //过滤text类型字段
  385. if ($v['DATA_TYPE'] != 'text')
  386. {
  387. //构造JS列信息
  388. $javascriptList[] = $this->getJsColumn($relationField);
  389. }
  390. }
  391. //JS最后一列加上操作列
  392. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  393. $addList = implode("\n", array_filter($addList));
  394. $editList = implode("\n", array_filter($editList));
  395. $javascriptList = implode(",\n", array_filter($javascriptList));
  396. $langList = implode(",\n", array_filter($langList));
  397. //表注释
  398. $tableComment = $tableInfo['Comment'];
  399. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  400. //最终将生成的文件路径
  401. $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
  402. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
  403. $addFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'add.html';
  404. $editFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'edit.html';
  405. $indexFile = $adminPath . 'view' . DS . $controllerUrl . DS . 'index.html';
  406. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
  407. $appNamespace = Config::get('app_namespace');
  408. $moduleName = 'admin';
  409. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  410. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  411. $data = [
  412. 'controllerNamespace' => $controllerNamespace,
  413. 'modelNamespace' => $modelNamespace,
  414. 'controllerUrl' => $controllerUrl,
  415. 'controllerDir' => $controllerDir,
  416. 'controllerName' => $controllerName,
  417. 'modelName' => $modelName,
  418. 'tableComment' => $tableComment,
  419. 'iconName' => $iconName,
  420. 'pk' => $priKey,
  421. 'order' => $order,
  422. 'table' => $table,
  423. 'tableName' => $tableName,
  424. 'addList' => $addList,
  425. 'editList' => $editList,
  426. 'javascriptList' => $javascriptList,
  427. 'langList' => $langList,
  428. 'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
  429. 'createTime' => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
  430. 'updateTime' => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
  431. 'modelTableName' => $table,
  432. 'relationModelTableName' => $relation,
  433. 'relationModelName' => $relationModelName,
  434. 'relationWith' => '',
  435. 'relationMethod' => '',
  436. 'relationModel' => '',
  437. 'relationForeignKey' => '',
  438. 'relationPrimaryKey' => '',
  439. 'relationSearch' => $relation ? 'true' : 'false',
  440. 'controllerIndex' => '',
  441. 'modelMethod' => '',
  442. ];
  443. //如果使用关联模型
  444. if ($relation)
  445. {
  446. //需要构造关联的方法
  447. $data['relationMethod'] = strtolower($relationModelName);
  448. //预载入的方法
  449. $data['relationWith'] = "->with('{$data['relationMethod']}')";
  450. //需要重写index方法
  451. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  452. //关联的模式
  453. $data['relationMode'] = $mode == 'hasone' ? 'hasOne' : 'belongsTo';
  454. //关联字段
  455. $data['relationForeignKey'] = $relationForeignKey;
  456. $data['relationPrimaryKey'] = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
  457. //构造关联模型的方法
  458. $data['modelMethod'] = $this->getReplacedStub('modelmethod', $data);
  459. }
  460. // 生成控制器文件
  461. $result = $this->writeToFile('controller', $data, $controllerFile);
  462. // 生成模型文件
  463. $result = $this->writeToFile('model', $data, $modelFile);
  464. if ($relation && !is_file($relationModelFile))
  465. {
  466. // 生成关联模型文件
  467. $result = $this->writeToFile('relationmodel', $data, $relationModelFile);
  468. }
  469. // 生成视图文件
  470. $result = $this->writeToFile('add', $data, $addFile);
  471. $result = $this->writeToFile('edit', $data, $editFile);
  472. $result = $this->writeToFile('index', $data, $indexFile);
  473. // 生成JS文件
  474. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  475. // 生成语言文件
  476. if ($langList)
  477. {
  478. $result = $this->writeToFile('lang', $data, $langFile);
  479. }
  480. }
  481. catch (\think\exception\ErrorException $e)
  482. {
  483. print_r($e);
  484. }
  485. $output->writeln("<info>Build Successed</info>");
  486. }
  487. protected function getModelName($model, $table)
  488. {
  489. if (!$model)
  490. {
  491. $modelarr = explode('_', strtolower($table));
  492. foreach ($modelarr as $k => &$v)
  493. $v = ucfirst($v);
  494. unset($v);
  495. $modelName = implode('', $modelarr);
  496. }
  497. else
  498. {
  499. $modelName = ucfirst($model);
  500. }
  501. return $modelName;
  502. }
  503. /**
  504. * 写入到文件
  505. * @param string $name
  506. * @param array $data
  507. * @param string $pathname
  508. * @return mixed
  509. */
  510. protected function writeToFile($name, $data, $pathname)
  511. {
  512. $content = $this->getReplacedStub($name, $data);
  513. if (!is_dir(dirname($pathname)))
  514. {
  515. mkdir(strtolower(dirname($pathname)), 0755, true);
  516. }
  517. return file_put_contents($pathname, $content);
  518. }
  519. /**
  520. * 获取替换后的数据
  521. * @param string $name
  522. * @param array $data
  523. * @return string
  524. */
  525. protected function getReplacedStub($name, $data)
  526. {
  527. $search = $replace = [];
  528. foreach ($data as $k => $v)
  529. {
  530. $search[] = "{%{$k}%}";
  531. $replace[] = $v;
  532. }
  533. $stub = file_get_contents($this->getStub($name));
  534. $content = str_replace($search, $replace, $stub);
  535. return $content;
  536. }
  537. /**
  538. * 获取基础模板
  539. * @param string $name
  540. * @return string
  541. */
  542. protected function getStub($name)
  543. {
  544. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  545. }
  546. protected function getLangItem($field, $content)
  547. {
  548. if (!Lang::has($field))
  549. {
  550. return <<<EOD
  551. '{$field}' => '{$content}'
  552. EOD;
  553. }
  554. else
  555. {
  556. return '';
  557. }
  558. }
  559. /**
  560. * 读取数据和语言数组列表
  561. * @param array $arr
  562. * @return array
  563. */
  564. protected function getLangArray($arr, $withTpl = TRUE)
  565. {
  566. $langArr = [];
  567. foreach ($arr as $k => $v)
  568. {
  569. $langArr[(is_numeric($k) ? $v : $k)] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  570. }
  571. return $langArr;
  572. }
  573. /**
  574. * 将数据转换成带字符串
  575. * @param array $arr
  576. * @return string
  577. */
  578. protected function getArrayString($arr)
  579. {
  580. $stringArr = [];
  581. foreach ($arr as $k => $v)
  582. {
  583. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  584. if (!$is_var)
  585. {
  586. $v = str_replace("'", "\'", $v);
  587. $k = str_replace("'", "\'", $k);
  588. }
  589. $stringArr[] = "'" . (is_numeric($k) ? $v : $k) . "' => " . (is_numeric($k) ? "__('" . ucfirst($k) . "')" : $is_var ? $v : "'{$v}'");
  590. }
  591. return implode(",", $stringArr);
  592. }
  593. protected function getFieldType(& $v)
  594. {
  595. $inputType = 'text';
  596. switch ($v['DATA_TYPE'])
  597. {
  598. case 'bigint':
  599. case 'int':
  600. case 'mediumint':
  601. case 'smallint':
  602. case 'tinyint':
  603. $inputType = 'number';
  604. break;
  605. case 'enum':
  606. case 'set':
  607. $inputType = 'select';
  608. break;
  609. case 'decimal':
  610. case 'double':
  611. case 'float':
  612. $inputType = 'number';
  613. break;
  614. case 'longtext':
  615. case 'text':
  616. case 'mediumtext':
  617. case 'smalltext':
  618. case 'tinytext':
  619. $inputType = 'textarea';
  620. break;
  621. case 'year';
  622. case 'date';
  623. case 'time';
  624. case 'datetime';
  625. case 'timestamp';
  626. $inputType = 'datetime';
  627. break;
  628. default:
  629. break;
  630. }
  631. $fieldsName = $v['COLUMN_NAME'];
  632. // 如果后缀以time结尾说明也是个时间字段
  633. if (substr($fieldsName, -4) == 'time')
  634. {
  635. $inputType = 'datetime';
  636. }
  637. // 如果后缀以data结尾且类型为enum,说明是个单选框
  638. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'enum')
  639. {
  640. $inputType = "radio";
  641. }
  642. // 如果后缀以data结尾且类型为set,说明是个复选框
  643. if (substr($fieldsName, -4) == 'data' && $v['DATA_TYPE'] == 'set')
  644. {
  645. $inputType = "checkbox";
  646. }
  647. return $inputType;
  648. }
  649. /**
  650. * 获取表单分组数据
  651. * @param string $field
  652. * @param string $content
  653. * @return string
  654. */
  655. protected function getFormGroup($field, $content)
  656. {
  657. $langField = ucfirst($field);
  658. return<<<EOD
  659. <div class="form-group">
  660. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  661. <div class="col-xs-12 col-sm-8">
  662. {$content}
  663. </div>
  664. </div>
  665. EOD;
  666. }
  667. /**
  668. * 获取图片模板数据
  669. * @param string $field
  670. * @param string $content
  671. * @return array
  672. */
  673. protected function getImageUpload($field, $content)
  674. {
  675. $filter = substr($field, -4) == 'avatar' || substr($field, -5) == 'image' || substr($field, -6) == 'images' ? ' data-mimetype="image/*"' : "";
  676. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  677. $preview = $filter ? ' data-preview-id="p-' . $field . '"' : '';
  678. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  679. return <<<EOD
  680. <div class="form-inline">
  681. {$content}
  682. <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>
  683. <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>
  684. {$previewcontainer}
  685. </div>
  686. EOD;
  687. }
  688. /**
  689. * 获取JS列数据
  690. * @param string $field
  691. * @return string
  692. */
  693. protected function getJsColumn($field)
  694. {
  695. $lang = ucfirst($field);
  696. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  697. $field = substr($field, stripos($field, '.') + 1);
  698. $formatter = '';
  699. if ($field == 'status')
  700. $formatter = 'status';
  701. else if ($field == 'icon')
  702. $formatter = 'icon';
  703. else if ($field == 'flag')
  704. $formatter = 'flag';
  705. else if (substr($field, -4) == 'time')
  706. $formatter = 'datetime';
  707. else if (substr($field, -3) == 'url')
  708. $formatter = 'url';
  709. else if (substr($field, -5) == 'image')
  710. $formatter = 'image';
  711. if ($formatter)
  712. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  713. else
  714. $html .= "}";
  715. return $html;
  716. }
  717. }