Crud.php 56 KB

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