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