Crud.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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. //构造JS列信息
  602. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  603. //排序方式,如果有指定排序字段,否则按主键排序
  604. $order = $field == $this->sortField ? $this->sortField : $order;
  605. }
  606. }
  607. //循环关联表,追加语言包和JS列
  608. foreach ($relations as $index => $relation) {
  609. foreach ($relation['relationColumnList'] as $k => $v) {
  610. // 不显示的字段直接过滤掉
  611. if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  612. continue;
  613. }
  614. $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  615. // 语言列表
  616. if ($v['COLUMN_COMMENT'] != '') {
  617. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  618. }
  619. //过滤text类型字段
  620. if ($v['DATA_TYPE'] != 'text') {
  621. //构造JS列信息
  622. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  623. }
  624. }
  625. }
  626. //JS最后一列加上操作列
  627. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  628. $addList = implode("\n", array_filter($addList));
  629. $editList = implode("\n", array_filter($editList));
  630. $javascriptList = implode(",\n", array_filter($javascriptList));
  631. $langList = implode(",\n", array_filter($langList));
  632. //表注释
  633. $tableComment = $modelTableInfo['Comment'];
  634. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  635. $appNamespace = Config::get('app_namespace');
  636. $moduleName = 'admin';
  637. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  638. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  639. $validateNamespace = "{$appNamespace}\\" . $moduleName . "\\validate";
  640. $validateName = $modelName;
  641. $modelInit = '';
  642. if ($priKey != $order) {
  643. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  644. }
  645. $data = [
  646. 'controllerNamespace' => $controllerNamespace,
  647. 'modelNamespace' => $modelNamespace,
  648. 'validateNamespace' => $validateNamespace,
  649. 'controllerUrl' => $controllerUrl,
  650. 'controllerDir' => $controllerDir,
  651. 'controllerName' => $controllerName,
  652. 'controllerAssignList' => implode("\n", $controllerAssignList),
  653. 'modelName' => $modelName,
  654. 'modelTableName' => $modelTableName,
  655. 'modelTableType' => $modelTableType,
  656. 'modelTableTypeName' => $modelTableTypeName,
  657. 'validateName' => $validateName,
  658. 'tableComment' => $tableComment,
  659. 'iconName' => $iconName,
  660. 'pk' => $priKey,
  661. 'order' => $order,
  662. 'table' => $table,
  663. 'tableName' => $modelTableName,
  664. 'addList' => $addList,
  665. 'editList' => $editList,
  666. 'javascriptList' => $javascriptList,
  667. 'langList' => $langList,
  668. 'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
  669. 'createTime' => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
  670. 'updateTime' => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
  671. 'relationSearch' => $relations ? 'true' : 'false',
  672. 'relationWithList' => '',
  673. 'relationMethodList' => '',
  674. 'controllerIndex' => '',
  675. 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '',
  676. 'appendAttrList' => implode(",\n", $appendAttrList),
  677. 'getEnumList' => implode("\n\n", $getEnumArr),
  678. 'getAttrList' => implode("\n\n", $getAttrArr),
  679. 'setAttrList' => implode("\n\n", $setAttrArr),
  680. 'modelInit' => $modelInit,
  681. ];
  682. //如果使用关联模型
  683. if ($relations) {
  684. $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  685. foreach ($relations as $index => $relation) {
  686. //需要构造关联的方法
  687. $relation['relationMethod'] = strtolower($relation['relationName']);
  688. //关联的模式
  689. $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
  690. //关联字段
  691. $relation['relationForeignKey'] = $relation['relationForeignKey'];
  692. $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  693. //预载入的方法
  694. $relationWithList[] = $relation['relationMethod'];
  695. unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  696. //构造关联模型的方法
  697. $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
  698. //显示的字段
  699. if ($relation['relationFields']) {
  700. $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  701. }
  702. }
  703. $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  704. $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  705. $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  706. //需要重写index方法
  707. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  708. } else if ($fields) {
  709. $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  710. //需要重写index方法
  711. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  712. }
  713. // 生成控制器文件
  714. $result = $this->writeToFile('controller', $data, $controllerFile);
  715. // 生成模型文件
  716. $result = $this->writeToFile('model', $data, $modelFile);
  717. if ($relations) {
  718. foreach ($relations as $i => $relation) {
  719. $relation['modelNamespace'] = $data['modelNamespace'];
  720. if (!is_file($relation['relationFile'])) {
  721. // 生成关联模型文件
  722. $result = $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  723. }
  724. }
  725. }
  726. // 生成验证文件
  727. $result = $this->writeToFile('validate', $data, $validateFile);
  728. // 生成视图文件
  729. $result = $this->writeToFile('add', $data, $addFile);
  730. $result = $this->writeToFile('edit', $data, $editFile);
  731. $result = $this->writeToFile('index', $data, $indexFile);
  732. // 生成JS文件
  733. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  734. // 生成语言文件
  735. if ($langList) {
  736. $result = $this->writeToFile('lang', $data, $langFile);
  737. }
  738. } catch (\think\exception\ErrorException $e) {
  739. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  740. }
  741. //继续生成菜单
  742. if ($menu) {
  743. exec("php think menu -c {$controllerUrl}");
  744. }
  745. $output->info("Build Successed");
  746. }
  747. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  748. {
  749. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  750. return;
  751. $fieldList = $this->getFieldListName($field);
  752. $methodName = 'get' . ucfirst($fieldList);
  753. foreach ($itemArr as $k => &$v) {
  754. $v = "__('" . mb_ucfirst($v) . "')";
  755. }
  756. unset($v);
  757. $itemString = $this->getArrayString($itemArr);
  758. $getEnum[] = <<<EOD
  759. public function {$methodName}()
  760. {
  761. return [{$itemString}];
  762. }
  763. EOD;
  764. $controllerAssignList[] = <<<EOD
  765. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  766. EOD;
  767. }
  768. protected function getAttr(&$getAttr, $field, $inputType = '')
  769. {
  770. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  771. return;
  772. $attrField = ucfirst($this->getCamelizeName($field));
  773. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  774. }
  775. protected function setAttr(&$setAttr, $field, $inputType = '')
  776. {
  777. if (!in_array($inputType, ['datetime', 'checkbox', 'select']))
  778. return;
  779. $attrField = ucfirst($this->getCamelizeName($field));
  780. if ($inputType == 'datetime') {
  781. $return = <<<EOD
  782. return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
  783. EOD;
  784. } else if (in_array($inputType, ['checkbox', 'select'])) {
  785. $return = <<<EOD
  786. return is_array(\$value) ? implode(',', \$value) : \$value;
  787. EOD;
  788. }
  789. $setAttr[] = <<<EOD
  790. protected function set{$attrField}Attr(\$value)
  791. {
  792. $return
  793. }
  794. EOD;
  795. }
  796. protected function appendAttr(&$appendAttrList, $field)
  797. {
  798. $appendAttrList[] = <<<EOD
  799. '{$field}_text'
  800. EOD;
  801. }
  802. protected function getModelName($model, $table)
  803. {
  804. if (!$model) {
  805. $modelarr = explode('_', strtolower($table));
  806. foreach ($modelarr as $k => &$v)
  807. $v = ucfirst($v);
  808. unset($v);
  809. $modelName = implode('', $modelarr);
  810. } else {
  811. $modelName = ucfirst($model);
  812. }
  813. return $modelName;
  814. }
  815. /**
  816. * 写入到文件
  817. * @param string $name
  818. * @param array $data
  819. * @param string $pathname
  820. * @return mixed
  821. */
  822. protected function writeToFile($name, $data, $pathname)
  823. {
  824. foreach ($data as $index => &$datum) {
  825. $datum = is_array($datum) ? '' : $datum;
  826. }
  827. unset($datum);
  828. $content = $this->getReplacedStub($name, $data);
  829. if (!is_dir(dirname($pathname))) {
  830. mkdir(strtolower(dirname($pathname)), 0755, true);
  831. }
  832. return file_put_contents($pathname, $content);
  833. }
  834. /**
  835. * 获取替换后的数据
  836. * @param string $name
  837. * @param array $data
  838. * @return string
  839. */
  840. protected function getReplacedStub($name, $data)
  841. {
  842. foreach ($data as $index => &$datum) {
  843. $datum = is_array($datum) ? '' : $datum;
  844. }
  845. unset($datum);
  846. $search = $replace = [];
  847. foreach ($data as $k => $v) {
  848. $search[] = "{%{$k}%}";
  849. $replace[] = $v;
  850. }
  851. $stubname = $this->getStub($name);
  852. if (isset($this->stubList[$stubname])) {
  853. $stub = $this->stubList[$stubname];
  854. } else {
  855. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  856. }
  857. $content = str_replace($search, $replace, $stub);
  858. return $content;
  859. }
  860. /**
  861. * 获取基础模板
  862. * @param string $name
  863. * @return string
  864. */
  865. protected function getStub($name)
  866. {
  867. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  868. }
  869. protected function getLangItem($field, $content)
  870. {
  871. if ($content || !Lang::has($field)) {
  872. $itemArr = [];
  873. $content = str_replace(',', ',', $content);
  874. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
  875. list($fieldLang, $item) = explode(':', $content);
  876. $itemArr = [$field => $fieldLang];
  877. foreach (explode(',', $item) as $k => $v) {
  878. $valArr = explode('=', $v);
  879. if (count($valArr) == 2) {
  880. list($key, $value) = $valArr;
  881. $itemArr[$field . ' ' . $key] = $value;
  882. }
  883. }
  884. } else {
  885. $itemArr = [$field => $content];
  886. }
  887. $resultArr = [];
  888. foreach ($itemArr as $k => $v) {
  889. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  890. }
  891. return implode(",\n", $resultArr);
  892. } else {
  893. return '';
  894. }
  895. }
  896. /**
  897. * 读取数据和语言数组列表
  898. * @param array $arr
  899. * @param boolean $withTpl
  900. * @return array
  901. */
  902. protected function getLangArray($arr, $withTpl = TRUE)
  903. {
  904. $langArr = [];
  905. foreach ($arr as $k => $v) {
  906. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  907. }
  908. return $langArr;
  909. }
  910. /**
  911. * 将数据转换成带字符串
  912. * @param array $arr
  913. * @return string
  914. */
  915. protected function getArrayString($arr)
  916. {
  917. if (!is_array($arr))
  918. return $arr;
  919. $stringArr = [];
  920. foreach ($arr as $k => $v) {
  921. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  922. if (!$is_var) {
  923. $v = str_replace("'", "\'", $v);
  924. $k = str_replace("'", "\'", $k);
  925. }
  926. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  927. }
  928. return implode(",", $stringArr);
  929. }
  930. protected function getItemArray($item, $field, $comment)
  931. {
  932. $itemArr = [];
  933. $comment = str_replace(',', ',', $comment);
  934. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  935. list($fieldLang, $item) = explode(':', $comment);
  936. $itemArr = [];
  937. foreach (explode(',', $item) as $k => $v) {
  938. $valArr = explode('=', $v);
  939. if (count($valArr) == 2) {
  940. list($key, $value) = $valArr;
  941. $itemArr[$key] = $field . ' ' . $key;
  942. }
  943. }
  944. } else {
  945. foreach ($item as $k => $v) {
  946. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  947. }
  948. }
  949. return $itemArr;
  950. }
  951. protected function getFieldType(& $v)
  952. {
  953. $inputType = 'text';
  954. switch ($v['DATA_TYPE']) {
  955. case 'bigint':
  956. case 'int':
  957. case 'mediumint':
  958. case 'smallint':
  959. case 'tinyint':
  960. $inputType = 'number';
  961. break;
  962. case 'enum':
  963. case 'set':
  964. $inputType = 'select';
  965. break;
  966. case 'decimal':
  967. case 'double':
  968. case 'float':
  969. $inputType = 'number';
  970. break;
  971. case 'longtext':
  972. case 'text':
  973. case 'mediumtext':
  974. case 'smalltext':
  975. case 'tinytext':
  976. $inputType = 'textarea';
  977. break;
  978. case 'year';
  979. case 'date';
  980. case 'time';
  981. case 'datetime';
  982. case 'timestamp';
  983. $inputType = 'datetime';
  984. break;
  985. default:
  986. break;
  987. }
  988. $fieldsName = $v['COLUMN_NAME'];
  989. // 指定后缀说明也是个时间字段
  990. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  991. $inputType = 'datetime';
  992. }
  993. // 指定后缀结尾且类型为enum,说明是个单选框
  994. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  995. $inputType = "radio";
  996. }
  997. // 指定后缀结尾且类型为set,说明是个复选框
  998. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  999. $inputType = "checkbox";
  1000. }
  1001. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1002. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1003. $inputType = "switch";
  1004. }
  1005. // 指定后缀结尾城市选择框
  1006. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1007. $inputType = "citypicker";
  1008. }
  1009. return $inputType;
  1010. }
  1011. /**
  1012. * 判断是否符合指定后缀
  1013. * @param string $field 字段名称
  1014. * @param mixed $suffixArr 后缀
  1015. * @return boolean
  1016. */
  1017. protected function isMatchSuffix($field, $suffixArr)
  1018. {
  1019. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1020. foreach ($suffixArr as $k => $v) {
  1021. if (preg_match("/{$v}$/i", $field)) {
  1022. return true;
  1023. }
  1024. }
  1025. return false;
  1026. }
  1027. /**
  1028. * 获取表单分组数据
  1029. * @param string $field
  1030. * @param string $content
  1031. * @return string
  1032. */
  1033. protected function getFormGroup($field, $content)
  1034. {
  1035. $langField = mb_ucfirst($field);
  1036. return <<<EOD
  1037. <div class="form-group">
  1038. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1039. <div class="col-xs-12 col-sm-8">
  1040. {$content}
  1041. </div>
  1042. </div>
  1043. EOD;
  1044. }
  1045. /**
  1046. * 获取图片模板数据
  1047. * @param string $field
  1048. * @param string $content
  1049. * @return array
  1050. */
  1051. protected function getImageUpload($field, $content)
  1052. {
  1053. $uploadfilter = $selectfilter = '';
  1054. if ($this->isMatchSuffix($field, $this->imageField)) {
  1055. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1056. $selectfilter = ' data-mimetype="image/*"';
  1057. }
  1058. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1059. $preview = $uploadfilter ? ' data-preview-id="p-' . $field . '"' : '';
  1060. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  1061. return <<<EOD
  1062. <div class="input-group">
  1063. {$content}
  1064. <div class="input-group-addon no-border no-padding">
  1065. <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>
  1066. <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>
  1067. </div>
  1068. <span class="msg-box n-right" for="c-{$field}"></span>
  1069. </div>
  1070. {$previewcontainer}
  1071. EOD;
  1072. }
  1073. /**
  1074. * 获取JS列数据
  1075. * @param string $field
  1076. * @param string $datatype
  1077. * @param string $extend
  1078. * @param array $itemArr
  1079. * @return string
  1080. */
  1081. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1082. {
  1083. $lang = mb_ucfirst($field);
  1084. $formatter = '';
  1085. foreach ($this->fieldFormatterSuffix as $k => $v) {
  1086. if (preg_match("/{$k}$/i", $field)) {
  1087. if (is_array($v)) {
  1088. if (in_array($datatype, $v['type'])) {
  1089. $formatter = $v['name'];
  1090. break;
  1091. }
  1092. } else {
  1093. $formatter = $v;
  1094. break;
  1095. }
  1096. }
  1097. }
  1098. if ($formatter) {
  1099. $extend = '';
  1100. }
  1101. $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
  1102. //$formatter = $extend ? '' : $formatter;
  1103. if ($extend) {
  1104. $html .= ", operate:false";
  1105. if ($datatype == 'set') {
  1106. $formatter = 'label';
  1107. }
  1108. }
  1109. foreach ($itemArr as $k => &$v) {
  1110. if (substr($v, 0, 3) !== '__(')
  1111. $v = "__('" . $v . "')";
  1112. }
  1113. unset($v);
  1114. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT);
  1115. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1116. if ($itemArr && !$extend) {
  1117. $html .= ", searchList: " . $searchList;
  1118. }
  1119. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1120. $html .= ", operate:'RANGE', addclass:'datetimerange'";
  1121. } else if (in_array($datatype, ['float', 'double', 'decimal'])) {
  1122. $html .= ", operate:'BETWEEN'";
  1123. }
  1124. if ($formatter)
  1125. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1126. else
  1127. $html .= "}";
  1128. if ($extend) {
  1129. $origin = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}'), visible:false";
  1130. if ($searchList) {
  1131. $origin .= ", searchList: " . $searchList;
  1132. }
  1133. $origin .= "}";
  1134. $html = $origin . ",\n" . $html;
  1135. }
  1136. return $html;
  1137. }
  1138. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1139. {
  1140. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1141. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1142. }
  1143. protected function getFieldListName($field)
  1144. {
  1145. return $this->getCamelizeName($field) . 'List';
  1146. }
  1147. }