Crud.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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\exception\ErrorException;
  12. use think\Lang;
  13. use think\Loader;
  14. class Crud extends Command
  15. {
  16. protected $stubList = [];
  17. protected $internalKeywords = [
  18. 'abstract',
  19. 'and',
  20. 'array',
  21. 'as',
  22. 'break',
  23. 'callable',
  24. 'case',
  25. 'catch',
  26. 'class',
  27. 'clone',
  28. 'const',
  29. 'continue',
  30. 'declare',
  31. 'default',
  32. 'die',
  33. 'do',
  34. 'echo',
  35. 'else',
  36. 'elseif',
  37. 'empty',
  38. 'enddeclare',
  39. 'endfor',
  40. 'endforeach',
  41. 'endif',
  42. 'endswitch',
  43. 'endwhile',
  44. 'eval',
  45. 'exit',
  46. 'extends',
  47. 'final',
  48. 'for',
  49. 'foreach',
  50. 'function',
  51. 'global',
  52. 'goto',
  53. 'if',
  54. 'implements',
  55. 'include',
  56. 'include_once',
  57. 'instanceof',
  58. 'insteadof',
  59. 'interface',
  60. 'isset',
  61. 'list',
  62. 'namespace',
  63. 'new',
  64. 'or',
  65. 'print',
  66. 'private',
  67. 'protected',
  68. 'public',
  69. 'require',
  70. 'require_once',
  71. 'return',
  72. 'static',
  73. 'switch',
  74. 'throw',
  75. 'trait',
  76. 'try',
  77. 'unset',
  78. 'use',
  79. 'var',
  80. 'while',
  81. 'xor'
  82. ];
  83. /**
  84. * 受保护的系统表, crud不会生效
  85. */
  86. protected $systemTables = [
  87. 'admin',
  88. 'admin_log',
  89. 'auth_group',
  90. 'auth_group_access',
  91. 'auth_rule',
  92. 'attachment',
  93. 'config',
  94. 'category',
  95. 'ems',
  96. 'sms',
  97. 'user',
  98. 'user_group',
  99. 'user_rule',
  100. 'user_score_log',
  101. 'user_token',
  102. ];
  103. /**
  104. * Selectpage搜索字段关联
  105. */
  106. protected $fieldSelectpageMap = [
  107. 'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids']
  108. ];
  109. /**
  110. * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表
  111. */
  112. protected $enumRadioSuffix = ['data', 'state', 'status'];
  113. /**
  114. * Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表
  115. */
  116. protected $setCheckboxSuffix = ['data', 'state', 'status'];
  117. /**
  118. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  119. */
  120. protected $intDateSuffix = ['time'];
  121. /**
  122. * 开关后缀
  123. */
  124. protected $switchSuffix = ['switch'];
  125. /**
  126. * 富文本后缀
  127. */
  128. protected $editorSuffix = ['content'];
  129. /**
  130. * 城市后缀
  131. */
  132. protected $citySuffix = ['city'];
  133. /**
  134. * 时间区间后缀
  135. */
  136. protected $rangeSuffix = ['range'];
  137. /**
  138. * JSON后缀
  139. */
  140. protected $jsonSuffix = ['json'];
  141. /**
  142. * 标签后缀
  143. */
  144. protected $tagSuffix = ['tag', 'tags'];
  145. /**
  146. * Selectpage对应的后缀
  147. */
  148. protected $selectpageSuffix = ['_id', '_ids'];
  149. /**
  150. * Selectpage多选对应的后缀
  151. */
  152. protected $selectpagesSuffix = ['_ids'];
  153. /**
  154. * 以指定字符结尾的字段格式化函数
  155. */
  156. protected $fieldFormatterSuffix = [
  157. 'status' => ['type' => ['varchar', 'enum'], 'name' => 'status'],
  158. 'icon' => 'icon',
  159. 'flag' => 'flag',
  160. 'url' => 'url',
  161. 'image' => 'image',
  162. 'images' => 'images',
  163. 'avatar' => 'image',
  164. 'switch' => 'toggle',
  165. 'tag' => 'flag',
  166. 'tags' => 'flag',
  167. 'time' => ['type' => ['int', 'timestamp'], 'name' => 'datetime'],
  168. ];
  169. /**
  170. * 识别为图片字段
  171. */
  172. protected $imageField = ['image', 'images', 'avatar', 'avatars'];
  173. /**
  174. * 识别为文件字段
  175. */
  176. protected $fileField = ['file', 'files'];
  177. /**
  178. * 保留字段
  179. */
  180. protected $reservedField = ['admin_id'];
  181. /**
  182. * 排除字段
  183. */
  184. protected $ignoreFields = [];
  185. /**
  186. * 排序字段
  187. */
  188. protected $sortField = 'weigh';
  189. /**
  190. * 筛选字段
  191. * @var string
  192. */
  193. protected $headingFilterField = 'status';
  194. /**
  195. * 添加时间字段
  196. * @var string
  197. */
  198. protected $createTimeField = 'createtime';
  199. /**
  200. * 更新时间字段
  201. * @var string
  202. */
  203. protected $updateTimeField = 'updatetime';
  204. /**
  205. * 软删除时间字段
  206. * @var string
  207. */
  208. protected $deleteTimeField = 'deletetime';
  209. /**
  210. * 编辑器的Class
  211. */
  212. protected $editorClass = 'editor';
  213. /**
  214. * langList的key最长字节数
  215. */
  216. protected $fieldMaxLen = 0;
  217. protected function configure()
  218. {
  219. $this
  220. ->setName('crud')
  221. ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
  222. ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
  223. ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
  224. ->addOption('fields', 'i', Option::VALUE_OPTIONAL, 'model visible fields', null)
  225. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override or force delete,without tips', null)
  226. ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
  227. ->addOption('relation', 'r', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table name without prefix', null)
  228. ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation model name', null)
  229. ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation foreign key', null)
  230. ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation primary key', null)
  231. ->addOption('relationfields', 's', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table fields', null)
  232. ->addOption('relationmode', 'o', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'relation table mode,hasone or belongsto', null)
  233. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
  234. ->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null)
  235. ->addOption('setcheckboxsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate checkbox component with suffix', null)
  236. ->addOption('enumradiosuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate radio component with suffix', null)
  237. ->addOption('imagefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate image component with suffix', null)
  238. ->addOption('filefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate file component with suffix', null)
  239. ->addOption('intdatesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate date component with suffix', null)
  240. ->addOption('switchsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate switch component with suffix', null)
  241. ->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null)
  242. ->addOption('jsonsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate fieldlist component with suffix', null)
  243. ->addOption('tagsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate tag component with suffix', null)
  244. ->addOption('editorsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate editor component with suffix', null)
  245. ->addOption('selectpagesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate selectpage component with suffix', null)
  246. ->addOption('selectpagessuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate multiple selectpage component with suffix', null)
  247. ->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null)
  248. ->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null)
  249. ->addOption('headingfilterfield', null, Option::VALUE_OPTIONAL, 'heading filter field', null)
  250. ->addOption('fixedcolumns', null, Option::VALUE_OPTIONAL, 'fixed columns', null)
  251. ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null)
  252. ->addOption('db', null, Option::VALUE_OPTIONAL, 'database config name', 'database')
  253. ->setDescription('Build CRUD controller and model from table');
  254. }
  255. protected function execute(Input $input, Output $output)
  256. {
  257. $adminPath = dirname(__DIR__) . DS;
  258. //数据库
  259. $db = $input->getOption('db');
  260. //表名
  261. $table = $input->getOption('table') ?: '';
  262. //自定义控制器
  263. $controller = $input->getOption('controller');
  264. //自定义模型
  265. $model = $input->getOption('model');
  266. $model = $model ? $model : $controller;
  267. //验证器类
  268. $validate = $model;
  269. //自定义显示字段
  270. $fields = $input->getOption('fields');
  271. //强制覆盖
  272. $force = $input->getOption('force');
  273. //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
  274. $local = $input->getOption('local');
  275. if (!$table) {
  276. throw new Exception('table name can\'t empty');
  277. }
  278. //是否生成菜单
  279. $menu = $input->getOption("menu");
  280. //关联表
  281. $relation = $input->getOption('relation');
  282. //自定义关联表模型
  283. $relationModels = $input->getOption('relationmodel');
  284. //模式
  285. $relationMode = $mode = $input->getOption('relationmode');
  286. //外键
  287. $relationForeignKey = $input->getOption('relationforeignkey');
  288. //主键
  289. $relationPrimaryKey = $input->getOption('relationprimarykey');
  290. //关联表显示字段
  291. $relationFields = $input->getOption('relationfields');
  292. //复选框后缀
  293. $setcheckboxsuffix = $input->getOption('setcheckboxsuffix');
  294. //单选框后缀
  295. $enumradiosuffix = $input->getOption('enumradiosuffix');
  296. //图片后缀
  297. $imagefield = $input->getOption('imagefield');
  298. //文件后缀
  299. $filefield = $input->getOption('filefield');
  300. //标签后缀
  301. $tagsuffix = $input->getOption('tagsuffix');
  302. //日期后缀
  303. $intdatesuffix = $input->getOption('intdatesuffix');
  304. //开关后缀
  305. $switchsuffix = $input->getOption('switchsuffix');
  306. //富文本编辑器
  307. $editorsuffix = $input->getOption('editorsuffix');
  308. //城市后缀
  309. $citysuffix = $input->getOption('citysuffix');
  310. //JSON配置后缀
  311. $jsonsuffix = $input->getOption('jsonsuffix');
  312. //selectpage后缀
  313. $selectpagesuffix = $input->getOption('selectpagesuffix');
  314. //selectpage多选后缀
  315. $selectpagessuffix = $input->getOption('selectpagessuffix');
  316. //排除字段
  317. $ignoreFields = $input->getOption('ignorefields');
  318. //排序字段
  319. $sortfield = $input->getOption('sortfield');
  320. //顶部筛选过滤字段
  321. $headingfilterfield = $input->getOption('headingfilterfield');
  322. //固定列数量
  323. $fixedcolumns = $input->getOption('fixedcolumns');
  324. //编辑器Class
  325. $editorclass = $input->getOption('editorclass');
  326. if ($setcheckboxsuffix) {
  327. $this->setCheckboxSuffix = $setcheckboxsuffix;
  328. }
  329. if ($enumradiosuffix) {
  330. $this->enumRadioSuffix = $enumradiosuffix;
  331. }
  332. if ($imagefield) {
  333. $this->imageField = $imagefield;
  334. }
  335. if ($filefield) {
  336. $this->fileField = $filefield;
  337. }
  338. if ($tagsuffix) {
  339. $this->tagSuffix = $tagsuffix;
  340. }
  341. if ($intdatesuffix) {
  342. $this->intDateSuffix = $intdatesuffix;
  343. }
  344. if ($switchsuffix) {
  345. $this->switchSuffix = $switchsuffix;
  346. }
  347. if ($editorsuffix) {
  348. $this->editorSuffix = $editorsuffix;
  349. }
  350. if ($citysuffix) {
  351. $this->citySuffix = $citysuffix;
  352. }
  353. if ($jsonsuffix) {
  354. $this->jsonSuffix = $jsonsuffix;
  355. }
  356. if ($selectpagesuffix) {
  357. $this->selectpageSuffix = $selectpagesuffix;
  358. }
  359. if ($selectpagessuffix) {
  360. $this->selectpagesSuffix = $selectpagessuffix;
  361. }
  362. if ($ignoreFields) {
  363. $this->ignoreFields = $ignoreFields;
  364. }
  365. if ($editorclass) {
  366. $this->editorClass = $editorclass;
  367. }
  368. if ($sortfield) {
  369. $this->sortField = $sortfield;
  370. }
  371. if ($headingfilterfield) {
  372. $this->headingFilterField = $headingfilterfield;
  373. }
  374. $this->reservedField = array_merge($this->reservedField, [$this->createTimeField, $this->updateTimeField, $this->deleteTimeField]);
  375. $dbconnect = Db::connect($db);
  376. $dbname = Config::get($db . '.database');
  377. $prefix = Config::get($db . '.prefix');
  378. //系统表无法生成,防止后台错乱
  379. if (in_array(str_replace($prefix, "", $table), $this->systemTables)) {
  380. throw new Exception('system table can\'t be crud');
  381. }
  382. //模块
  383. $moduleName = 'admin';
  384. $modelModuleName = $local ? $moduleName : 'common';
  385. $validateModuleName = $local ? $moduleName : 'common';
  386. //检查主表
  387. $modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
  388. $modelTableType = 'table';
  389. $modelTableTypeName = $modelTableName = $modelName;
  390. $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  391. if (!$modelTableInfo) {
  392. $modelTableType = 'name';
  393. $modelTableName = $prefix . $modelName;
  394. $modelTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  395. if (!$modelTableInfo) {
  396. throw new Exception("table not found");
  397. }
  398. }
  399. $modelTableInfo = $modelTableInfo[0];
  400. $relations = [];
  401. //检查关联表
  402. if ($relation) {
  403. $relationArr = $relation;
  404. $relations = [];
  405. foreach ($relationArr as $index => $relationTable) {
  406. $relationName = stripos($relationTable, $prefix) === 0 ? substr($relationTable, strlen($prefix)) : $relationTable;
  407. $relationTableType = 'table';
  408. $relationTableTypeName = $relationTableName = $relationName;
  409. $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
  410. if (!$relationTableInfo) {
  411. $relationTableType = 'name';
  412. $relationTableName = $prefix . $relationName;
  413. $relationTableInfo = $dbconnect->query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], true);
  414. if (!$relationTableInfo) {
  415. throw new Exception("relation table not found");
  416. }
  417. }
  418. $relationTableInfo = $relationTableInfo[0];
  419. $relationModel = isset($relationModels[$index]) ? $relationModels[$index] : '';
  420. list($relationNamespace, $relationName, $relationFile) = $this->getModelData($modelModuleName, $relationModel, $relationName);
  421. $relations[] = [
  422. //关联表基础名
  423. 'relationName' => $relationName,
  424. //关联表类命名空间
  425. 'relationNamespace' => $relationNamespace,
  426. //关联模型名
  427. 'relationModel' => $relationModel,
  428. //关联文件
  429. 'relationFile' => $relationFile,
  430. //关联表名称
  431. 'relationTableName' => $relationTableName,
  432. //关联表信息
  433. 'relationTableInfo' => $relationTableInfo,
  434. //关联模型表类型(name或table)
  435. 'relationTableType' => $relationTableType,
  436. //关联模型表类型名称
  437. 'relationTableTypeName' => $relationTableTypeName,
  438. //关联模式
  439. 'relationFields' => isset($relationFields[$index]) ? explode(',', $relationFields[$index]) : [],
  440. //关联模式
  441. 'relationMode' => isset($relationMode[$index]) ? $relationMode[$index] : 'belongsto',
  442. //关联表外键
  443. 'relationForeignKey' => isset($relationForeignKey[$index]) ? $relationForeignKey[$index] : Loader::parseName($relationName) . '_id',
  444. //关联表主键
  445. 'relationPrimaryKey' => isset($relationPrimaryKey[$index]) ? $relationPrimaryKey[$index] : '',
  446. ];
  447. }
  448. }
  449. //根据表名匹配对应的Fontawesome图标
  450. $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
  451. $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o';
  452. //控制器
  453. list($controllerNamespace, $controllerName, $controllerFile, $controllerArr) = $this->getControllerData($moduleName, $controller, $table);
  454. //模型
  455. list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($modelModuleName, $model, $table);
  456. //验证器
  457. list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($validateModuleName, $validate, $table);
  458. //处理基础文件名,取消所有下划线并转换为小写
  459. $baseNameArr = $controllerArr;
  460. $baseFileName = Loader::parseName(array_pop($baseNameArr), 0);
  461. array_push($baseNameArr, $baseFileName);
  462. $controllerBaseName = strtolower(implode(DS, $baseNameArr));
  463. $controllerUrl = strtolower(implode('/', $baseNameArr));
  464. //视图文件
  465. $viewArr = $controllerArr;
  466. $lastValue = array_pop($viewArr);
  467. $viewArr[] = Loader::parseName($lastValue, 0);
  468. array_unshift($viewArr, 'view');
  469. $viewDir = $adminPath . strtolower(implode(DS, $viewArr)) . DS;
  470. //最终将生成的文件路径
  471. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerBaseName . '.js';
  472. $addFile = $viewDir . 'add.html';
  473. $editFile = $viewDir . 'edit.html';
  474. $indexFile = $viewDir . 'index.html';
  475. $recyclebinFile = $viewDir . 'recyclebin.html';
  476. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerBaseName . '.php';
  477. //是否为删除模式
  478. $delete = $input->getOption('delete');
  479. if ($delete) {
  480. $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $recyclebinFile, $langFile, $javascriptFile];
  481. foreach ($readyFiles as $k => $v) {
  482. $output->warning($v);
  483. }
  484. if (!$force) {
  485. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  486. $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
  487. if (trim($line) != 'yes') {
  488. throw new Exception("Operation is aborted!");
  489. }
  490. }
  491. foreach ($readyFiles as $k => $v) {
  492. if (file_exists($v)) {
  493. unlink($v);
  494. }
  495. //删除空文件夹
  496. switch ($v) {
  497. case $modelFile:
  498. $this->removeEmptyBaseDir($v, $modelArr);
  499. break;
  500. case $validateFile:
  501. $this->removeEmptyBaseDir($v, $validateArr);
  502. break;
  503. case $addFile:
  504. case $editFile:
  505. case $indexFile:
  506. case $recyclebinFile:
  507. $this->removeEmptyBaseDir($v, $viewArr);
  508. break;
  509. default:
  510. $this->removeEmptyBaseDir($v, $controllerArr);
  511. }
  512. }
  513. //继续删除菜单
  514. if ($menu) {
  515. exec("php think menu -c {$controllerUrl} -d 1 -f 1");
  516. }
  517. $output->info("Delete Successed");
  518. return;
  519. }
  520. //非覆盖模式时如果存在控制器文件则报错
  521. if (is_file($controllerFile) && !$force) {
  522. throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  523. }
  524. //非覆盖模式时如果存在模型文件则报错
  525. if (is_file($modelFile) && !$force) {
  526. throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  527. }
  528. //非覆盖模式时如果存在验证文件则报错
  529. if (is_file($validateFile) && !$force) {
  530. throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  531. }
  532. require $adminPath . 'common.php';
  533. //从数据库中获取表字段信息
  534. $sql = "SELECT * FROM `information_schema`.`columns` "
  535. . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  536. . "ORDER BY ORDINAL_POSITION";
  537. //加载主表的列
  538. $columnList = $dbconnect->query($sql, [$dbname, $modelTableName]);
  539. $fieldArr = [];
  540. foreach ($columnList as $k => $v) {
  541. $fieldArr[] = $v['COLUMN_NAME'];
  542. }
  543. // 加载关联表的列
  544. foreach ($relations as $index => &$relation) {
  545. $relationColumnList = $dbconnect->query($sql, [$dbname, $relation['relationTableName']]);
  546. $relationFieldList = [];
  547. foreach ($relationColumnList as $k => $v) {
  548. $relationFieldList[] = $v['COLUMN_NAME'];
  549. }
  550. if (!$relation['relationPrimaryKey']) {
  551. foreach ($relationColumnList as $k => $v) {
  552. if ($v['COLUMN_KEY'] == 'PRI') {
  553. $relation['relationPrimaryKey'] = $v['COLUMN_NAME'];
  554. break;
  555. }
  556. }
  557. }
  558. // 如果主键为空
  559. if (!$relation['relationPrimaryKey']) {
  560. throw new Exception('Relation Primary key not found!');
  561. }
  562. // 如果主键不在表字段中
  563. if (!in_array($relation['relationPrimaryKey'], $relationFieldList)) {
  564. throw new Exception('Relation Primary key not found in table!');
  565. }
  566. $relation['relationColumnList'] = $relationColumnList;
  567. $relation['relationFieldList'] = $relationFieldList;
  568. }
  569. unset($relation);
  570. $addList = [];
  571. $editList = [];
  572. $javascriptList = [];
  573. $langList = [];
  574. $field = 'id';
  575. $order = 'id';
  576. $priDefined = false;
  577. $priKey = '';
  578. $relationPrimaryKey = '';
  579. foreach ($columnList as $k => $v) {
  580. if ($v['COLUMN_KEY'] == 'PRI') {
  581. $priKey = $v['COLUMN_NAME'];
  582. break;
  583. }
  584. }
  585. if (!$priKey) {
  586. throw new Exception('Primary key not found!');
  587. }
  588. $order = $priKey;
  589. //如果是关联模型
  590. foreach ($relations as $index => &$relation) {
  591. if ($relation['relationMode'] == 'hasone') {
  592. $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id";
  593. $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  594. if (!in_array($relationForeignKey, $relation['relationFieldList'])) {
  595. throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']');
  596. }
  597. if (!in_array($relationPrimaryKey, $fieldArr)) {
  598. throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']');
  599. }
  600. } else {
  601. $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id";
  602. $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey'];
  603. if (!in_array($relationForeignKey, $fieldArr)) {
  604. throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']');
  605. }
  606. if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) {
  607. throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']');
  608. }
  609. }
  610. $relation['relationForeignKey'] = $relationForeignKey;
  611. $relation['relationPrimaryKey'] = $relationPrimaryKey;
  612. $relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName'];
  613. }
  614. unset($relation);
  615. try {
  616. Form::setEscapeHtml(false);
  617. $setAttrArr = [];
  618. $getAttrArr = [];
  619. $getEnumArr = [];
  620. $appendAttrList = [];
  621. $controllerAssignList = [];
  622. $headingHtml = '{:build_heading()}';
  623. $recyclebinHtml = '';
  624. //循环所有字段,开始构造视图的HTML和JS信息
  625. foreach ($columnList as $k => $v) {
  626. $field = $v['COLUMN_NAME'];
  627. $itemArr = [];
  628. // 这里构建Enum和Set类型的列表数据
  629. if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
  630. if ($v['DATA_TYPE'] !== 'tinyint') {
  631. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  632. $itemArr = explode(',', str_replace("'", '', $itemArr));
  633. }
  634. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  635. //如果类型为tinyint且有使用备注数据
  636. if ($itemArr && $v['DATA_TYPE'] == 'tinyint') {
  637. $v['DATA_TYPE'] = 'enum';
  638. }
  639. }
  640. // 语言列表
  641. if ($v['COLUMN_COMMENT'] != '') {
  642. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  643. }
  644. $inputType = '';
  645. //保留字段不能修改和添加
  646. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) {
  647. $inputType = $this->getFieldType($v);
  648. // 如果是number类型时增加一个步长
  649. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  650. $attrArr = ['id' => "c-{$field}"];
  651. $cssClassArr = ['form-control'];
  652. $fieldName = "row[{$field}]";
  653. $defaultValue = $v['COLUMN_DEFAULT'];
  654. $editValue = "{\$row.{$field}|htmlentities}";
  655. // 如果默认值非null,则是一个必选项
  656. if ($v['IS_NULLABLE'] == 'NO') {
  657. $attrArr['data-rule'] = 'required';
  658. }
  659. //如果字段类型为无符号型,则设置<input min=0>
  660. if (stripos($v['COLUMN_TYPE'], 'unsigned') !== false) {
  661. $attrArr['min'] = 0;
  662. }
  663. if ($inputType == 'select') {
  664. $cssClassArr[] = 'selectpicker';
  665. $attrArr['class'] = implode(' ', $cssClassArr);
  666. if ($v['DATA_TYPE'] == 'set') {
  667. $attrArr['multiple'] = '';
  668. $fieldName .= "[]";
  669. }
  670. $attrArr['name'] = $fieldName;
  671. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  672. $itemArr = $this->getLangArray($itemArr, false);
  673. //添加一个获取器
  674. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  675. if ($v['DATA_TYPE'] == 'set') {
  676. $this->setAttr($setAttrArr, $field, $inputType);
  677. }
  678. $this->appendAttr($appendAttrList, $field);
  679. $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  680. $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  681. } elseif ($inputType == 'datetime') {
  682. $cssClassArr[] = 'datetimepicker';
  683. $attrArr['class'] = implode(' ', $cssClassArr);
  684. $format = "YYYY-MM-DD HH:mm:ss";
  685. $phpFormat = "Y-m-d H:i:s";
  686. $fieldFunc = '';
  687. switch ($v['DATA_TYPE']) {
  688. case 'year':
  689. $format = "YYYY";
  690. $phpFormat = 'Y';
  691. break;
  692. case 'date':
  693. $format = "YYYY-MM-DD";
  694. $phpFormat = 'Y-m-d';
  695. break;
  696. case 'time':
  697. $format = "HH:mm:ss";
  698. $phpFormat = 'H:i:s';
  699. break;
  700. case 'timestamp':
  701. $fieldFunc = 'datetime';
  702. // no break
  703. case 'datetime':
  704. $format = "YYYY-MM-DD HH:mm:ss";
  705. $phpFormat = 'Y-m-d H:i:s';
  706. break;
  707. default:
  708. $fieldFunc = 'datetime';
  709. $this->getAttr($getAttrArr, $field, $inputType);
  710. $this->setAttr($setAttrArr, $field, $inputType);
  711. $this->appendAttr($appendAttrList, $field);
  712. break;
  713. }
  714. $defaultDateTime = "{:date('{$phpFormat}')}";
  715. $attrArr['data-date-format'] = $format;
  716. $attrArr['data-use-current'] = "true";
  717. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  718. $formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr);
  719. } elseif ($inputType == 'datetimerange') {
  720. $cssClassArr[] = 'datetimerange';
  721. $attrArr['class'] = implode(' ', $cssClassArr);
  722. $attrArr['data-locale'] = '{"format":"YYYY-MM-DD HH:mm:ss"}';
  723. $fieldFunc = '';
  724. $defaultDateTime = "";
  725. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  726. $formEditElement = Form::text($fieldName, $editValue, $attrArr);
  727. } elseif ($inputType == 'checkbox' || $inputType == 'radio') {
  728. unset($attrArr['data-rule']);
  729. $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
  730. $attrArr['name'] = "row[{$fieldName}]";
  731. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
  732. $itemArr = $this->getLangArray($itemArr, false);
  733. //添加一个获取器
  734. $this->getAttr($getAttrArr, $field, $inputType);
  735. if ($inputType == 'checkbox') {
  736. $this->setAttr($setAttrArr, $field, $inputType);
  737. }
  738. $this->appendAttr($appendAttrList, $field);
  739. $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
  740. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  741. $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  742. } elseif ($inputType == 'textarea' && !$this->isMatchSuffix($field, $this->selectpagesSuffix) && !$this->isMatchSuffix($field, $this->imageField)) {
  743. $cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : '';
  744. $attrArr['class'] = implode(' ', $cssClassArr);
  745. $attrArr['rows'] = 5;
  746. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  747. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  748. } elseif ($inputType == 'switch') {
  749. unset($attrArr['data-rule']);
  750. if ($defaultValue === '1' || $defaultValue === 'Y') {
  751. $yes = $defaultValue;
  752. $no = $defaultValue === '1' ? '0' : 'N';
  753. } else {
  754. $no = $defaultValue;
  755. $yes = $defaultValue === '0' ? '1' : 'Y';
  756. }
  757. if (!$itemArr) {
  758. $itemArr = [$yes => 'Yes', $no => 'No'];
  759. }
  760. $stateNoClass = 'fa-flip-horizontal text-gray';
  761. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
  762. $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => "{\$row.{$field}}", 'fieldSwitchClass' => "{eq name=\"\$row.{$field}\" value=\"{$no}\"}fa-flip-horizontal text-gray{/eq}"]);
  763. } elseif ($inputType == 'citypicker') {
  764. $attrArr['class'] = implode(' ', $cssClassArr);
  765. $attrArr['data-toggle'] = "city-picker";
  766. $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
  767. $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
  768. } elseif ($inputType == 'tagsinput') {
  769. $attrArr['class'] = implode(' ', $cssClassArr);
  770. $attrArr['data-role'] = "tagsinput";
  771. $formAddElement = Form::input('text', $fieldName, $defaultValue, $attrArr);
  772. $formEditElement = Form::input('text', $fieldName, $editValue, $attrArr);
  773. } elseif ($inputType == 'fieldlist') {
  774. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  775. $templateName = !isset($itemArr['key']) && !isset($itemArr['value']) && count($itemArr) > 0 ? 'fieldlist-template' : 'fieldlist';
  776. $itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key';
  777. $itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value';
  778. $theadListArr = $tbodyListArr = [];
  779. foreach ($itemArr as $index => $item) {
  780. $theadListArr[] = "<td>{:__('" . $item . "')}</td>";
  781. $tbodyListArr[] = '<td><input type="text" name="<%=name%>[<%=index%>][' . $index . ']" class="form-control" value="<%=row.' . $index . '%>"/></td>';
  782. }
  783. $colspan = count($theadListArr) + 1;
  784. $commonFields = ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'theadList' => implode("\n", $theadListArr), 'tbodyList' => implode("\n", $tbodyListArr), 'colspan' => $colspan];
  785. $formAddElement = $this->getReplacedStub('html/' . $templateName, array_merge($commonFields, ['fieldValue' => $defaultValue]));
  786. $formEditElement = $this->getReplacedStub('html/' . $templateName, array_merge($commonFields, ['fieldValue' => $editValue]));
  787. } else {
  788. $search = $replace = '';
  789. //特殊字段为关联搜索
  790. if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
  791. $inputType = 'text';
  792. $defaultValue = '';
  793. $attrArr['data-rule'] = 'required';
  794. $cssClassArr[] = 'selectpage';
  795. $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
  796. $attrArr['data-source'] = $selectpageController . "/index";
  797. //如果是类型表需要特殊处理下
  798. if ($selectpageController == 'category') {
  799. $attrArr['data-source'] = 'category/selectpage';
  800. $attrArr['data-params'] = '##replacetext##';
  801. $search = '"##replacetext##"';
  802. $replace = '\'{"custom[type]":"' . $table . '"}\'';
  803. } elseif ($selectpageController == 'admin') {
  804. $attrArr['data-source'] = 'auth/admin/selectpage';
  805. } elseif ($selectpageController == 'user') {
  806. $attrArr['data-source'] = 'user/user/index';
  807. }
  808. if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
  809. $attrArr['data-multiple'] = 'true';
  810. }
  811. foreach ($this->fieldSelectpageMap as $m => $n) {
  812. if (in_array($field, $n)) {
  813. $attrArr['data-field'] = $m;
  814. break;
  815. }
  816. }
  817. }
  818. //因为有自动完成可输入其它内容
  819. $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  820. $attrArr['class'] = implode(' ', $cssClassArr);
  821. $isUpload = false;
  822. if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
  823. $isUpload = true;
  824. }
  825. //如果是步长则加上步长
  826. if ($step) {
  827. $attrArr['step'] = $step;
  828. }
  829. //如果是图片加上个size
  830. if ($isUpload) {
  831. $attrArr['size'] = 50;
  832. }
  833. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  834. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  835. if ($search && $replace) {
  836. $formAddElement = str_replace($search, $replace, $formAddElement);
  837. $formEditElement = str_replace($search, $replace, $formEditElement);
  838. }
  839. //如果是图片或文件
  840. if ($isUpload) {
  841. $formAddElement = $this->getImageUpload($field, $formAddElement);
  842. $formEditElement = $this->getImageUpload($field, $formEditElement);
  843. }
  844. }
  845. //构造添加和编辑HTML信息
  846. $addList[] = $this->getFormGroup($field, $formAddElement);
  847. $editList[] = $this->getFormGroup($field, $formEditElement);
  848. }
  849. //过滤text类型字段
  850. if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
  851. //主键
  852. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
  853. $priDefined = true;
  854. $javascriptList[] = "{checkbox: true}";
  855. }
  856. if ($this->deleteTimeField == $field) {
  857. $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
  858. continue;
  859. }
  860. if (!$fields || in_array($field, explode(',', $fields))) {
  861. //构造JS列信息
  862. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  863. }
  864. if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
  865. $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
  866. }
  867. //排序方式,如果有指定排序字段,否则按主键排序
  868. $order = $field == $this->sortField ? $this->sortField : $order;
  869. }
  870. }
  871. //循环关联表,追加语言包和JS列
  872. foreach ($relations as $index => $relation) {
  873. foreach ($relation['relationColumnList'] as $k => $v) {
  874. // 不显示的字段直接过滤掉
  875. if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  876. continue;
  877. }
  878. $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  879. // 语言列表
  880. if ($v['COLUMN_COMMENT'] != '') {
  881. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  882. }
  883. //过滤text类型字段
  884. if ($v['DATA_TYPE'] != 'text') {
  885. //构造JS列信息
  886. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  887. }
  888. }
  889. }
  890. //JS最后一列加上操作列
  891. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  892. $addList = implode("\n", array_filter($addList));
  893. $editList = implode("\n", array_filter($editList));
  894. $javascriptList = implode(",\n", array_filter($javascriptList));
  895. $langList = implode(",\n", array_filter($langList));
  896. //数组等号对齐
  897. $langList = array_filter(explode(",\n", $langList . ",\n"));
  898. foreach ($langList as &$line) {
  899. if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
  900. $line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
  901. }
  902. }
  903. unset($line);
  904. $langList = implode(",\n", array_filter($langList));
  905. $fixedcolumns = count($columnList) >= 10 ? 1 : $fixedcolumns;
  906. $fixedColumnsJs = '';
  907. if (is_numeric($fixedcolumns) && $fixedcolumns) {
  908. $fixedColumnsJs = "\n" . str_repeat(" ", 16) . "fixedColumns: true,\n" . str_repeat(" ", 16) . ($fixedcolumns < 0 ? "fixedNumber" : "fixedRightNumber") . ": " . $fixedcolumns . ",";
  909. }
  910. //表注释
  911. $tableComment = $modelTableInfo['Comment'];
  912. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  913. $modelInit = '';
  914. if ($priKey != $order) {
  915. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  916. }
  917. $data = [
  918. 'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';",
  919. 'controllerNamespace' => $controllerNamespace,
  920. 'modelNamespace' => $modelNamespace,
  921. 'validateNamespace' => $validateNamespace,
  922. 'controllerUrl' => $controllerUrl,
  923. 'controllerName' => $controllerName,
  924. 'controllerAssignList' => implode("\n", $controllerAssignList),
  925. 'modelName' => $modelName,
  926. 'modelTableName' => $modelTableName,
  927. 'modelTableType' => $modelTableType,
  928. 'modelTableTypeName' => $modelTableTypeName,
  929. 'validateName' => $validateName,
  930. 'tableComment' => $tableComment,
  931. 'iconName' => $iconName,
  932. 'pk' => $priKey,
  933. 'order' => $order,
  934. 'fixedColumnsJs' => $fixedColumnsJs,
  935. 'table' => $table,
  936. 'tableName' => $modelTableName,
  937. 'addList' => $addList,
  938. 'editList' => $editList,
  939. 'javascriptList' => $javascriptList,
  940. 'langList' => $langList,
  941. 'softDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
  942. 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  943. 'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false',
  944. 'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
  945. 'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
  946. 'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
  947. 'relationSearch' => $relations ? 'true' : 'false',
  948. 'relationWithList' => '',
  949. 'relationMethodList' => '',
  950. 'controllerIndex' => '',
  951. 'recyclebinJs' => '',
  952. 'headingHtml' => $headingHtml,
  953. 'recyclebinHtml' => $recyclebinHtml,
  954. 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(in_array($priKey, explode(',', $fields)) ? explode(',', $fields) : explode(',', $priKey . ',' . $fields))) . "']);" : '',
  955. 'appendAttrList' => implode(",\n", $appendAttrList),
  956. 'getEnumList' => implode("\n\n", $getEnumArr),
  957. 'getAttrList' => implode("\n\n", $getAttrArr),
  958. 'setAttrList' => implode("\n\n", $setAttrArr),
  959. 'modelInit' => $modelInit,
  960. ];
  961. //如果使用关联模型
  962. if ($relations) {
  963. $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  964. foreach ($relations as $index => $relation) {
  965. //需要构造关联的方法
  966. $relation['relationMethod'] = strtolower($relation['relationName']);
  967. //关联的模式
  968. $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
  969. //关联字段
  970. $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  971. //预载入的方法
  972. $relationWithList[] = $relation['relationMethod'];
  973. unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  974. //构造关联模型的方法
  975. $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
  976. //如果设置了显示主表字段,则必须显式将关联表字段显示
  977. if ($fields) {
  978. $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
  979. }
  980. //显示的字段
  981. if ($relation['relationFields']) {
  982. $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  983. }
  984. }
  985. $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  986. $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  987. $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  988. //需要重写index方法
  989. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  990. } elseif ($fields) {
  991. $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  992. //需要重写index方法
  993. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  994. }
  995. // 生成控制器文件
  996. $this->writeToFile('controller', $data, $controllerFile);
  997. // 生成模型文件
  998. $this->writeToFile('model', $data, $modelFile);
  999. if ($relations) {
  1000. foreach ($relations as $i => $relation) {
  1001. $relation['modelNamespace'] = $relation['relationNamespace'];
  1002. if (!is_file($relation['relationFile'])) {
  1003. // 生成关联模型文件
  1004. $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  1005. }
  1006. }
  1007. }
  1008. // 生成验证文件
  1009. $this->writeToFile('validate', $data, $validateFile);
  1010. // 生成视图文件
  1011. $this->writeToFile('add', $data, $addFile);
  1012. $this->writeToFile('edit', $data, $editFile);
  1013. $this->writeToFile('index', $data, $indexFile);
  1014. if ($recyclebinHtml) {
  1015. $this->writeToFile('recyclebin', $data, $recyclebinFile);
  1016. $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
  1017. $recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
  1018. $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['deleteTimeField' => $this->deleteTimeField, 'recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
  1019. }
  1020. // 生成JS文件
  1021. $this->writeToFile('javascript', $data, $javascriptFile);
  1022. // 生成语言文件
  1023. $this->writeToFile('lang', $data, $langFile);
  1024. } catch (ErrorException $e) {
  1025. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  1026. }
  1027. //继续生成菜单
  1028. if ($menu) {
  1029. exec("php think menu -c {$controllerUrl}");
  1030. }
  1031. $output->info("Build Successed");
  1032. }
  1033. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  1034. {
  1035. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1036. return;
  1037. }
  1038. $fieldList = $this->getFieldListName($field);
  1039. $methodName = 'get' . ucfirst($fieldList);
  1040. foreach ($itemArr as $k => &$v) {
  1041. $v = "__('" . mb_ucfirst($v) . "')";
  1042. }
  1043. unset($v);
  1044. $itemString = $this->getArrayString($itemArr);
  1045. $getEnum[] = <<<EOD
  1046. public function {$methodName}()
  1047. {
  1048. return [{$itemString}];
  1049. }
  1050. EOD;
  1051. $controllerAssignList[] = <<<EOD
  1052. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  1053. EOD;
  1054. }
  1055. protected function getAttr(&$getAttr, $field, $inputType = '')
  1056. {
  1057. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1058. return;
  1059. }
  1060. $attrField = ucfirst($this->getCamelizeName($field));
  1061. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  1062. }
  1063. protected function setAttr(&$setAttr, $field, $inputType = '')
  1064. {
  1065. if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
  1066. return;
  1067. }
  1068. $attrField = ucfirst($this->getCamelizeName($field));
  1069. if ($inputType == 'datetime') {
  1070. $return = <<<EOD
  1071. return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  1072. EOD;
  1073. } elseif (in_array($inputType, ['checkbox', 'select'])) {
  1074. $return = <<<EOD
  1075. return is_array(\$value) ? implode(',', \$value) : \$value;
  1076. EOD;
  1077. }
  1078. $setAttr[] = <<<EOD
  1079. protected function set{$attrField}Attr(\$value)
  1080. {
  1081. $return
  1082. }
  1083. EOD;
  1084. }
  1085. protected function appendAttr(&$appendAttrList, $field)
  1086. {
  1087. $appendAttrList[] = <<<EOD
  1088. '{$field}_text'
  1089. EOD;
  1090. }
  1091. /**
  1092. * 移除相对的空目录
  1093. * @param $parseFile
  1094. * @param $parseArr
  1095. * @return bool
  1096. */
  1097. protected function removeEmptyBaseDir($parseFile, $parseArr)
  1098. {
  1099. if (count($parseArr) > 1) {
  1100. $parentDir = dirname($parseFile);
  1101. for ($i = 0; $i < count($parseArr); $i++) {
  1102. try {
  1103. $iterator = new \FilesystemIterator($parentDir);
  1104. $isDirEmpty = !$iterator->valid();
  1105. if ($isDirEmpty) {
  1106. rmdir($parentDir);
  1107. $parentDir = dirname($parentDir);
  1108. } else {
  1109. return true;
  1110. }
  1111. } catch (\UnexpectedValueException $e) {
  1112. return false;
  1113. }
  1114. }
  1115. }
  1116. return true;
  1117. }
  1118. /**
  1119. * 获取控制器相关信息
  1120. * @param $module
  1121. * @param $controller
  1122. * @param $table
  1123. * @return array
  1124. */
  1125. protected function getControllerData($module, $controller, $table)
  1126. {
  1127. return $this->getParseNameData($module, $controller, $table, 'controller');
  1128. }
  1129. /**
  1130. * 获取模型相关信息
  1131. * @param $module
  1132. * @param $model
  1133. * @param $table
  1134. * @return array
  1135. */
  1136. protected function getModelData($module, $model, $table)
  1137. {
  1138. return $this->getParseNameData($module, $model, $table, 'model');
  1139. }
  1140. /**
  1141. * 获取验证器相关信息
  1142. * @param $module
  1143. * @param $validate
  1144. * @param $table
  1145. * @return array
  1146. */
  1147. protected function getValidateData($module, $validate, $table)
  1148. {
  1149. return $this->getParseNameData($module, $validate, $table, 'validate');
  1150. }
  1151. /**
  1152. * 获取已解析相关信息
  1153. * @param string $module 模块名称
  1154. * @param string $name 自定义名称
  1155. * @param string $table 数据表名
  1156. * @param string $type 解析类型,本例中为controller、model、validate
  1157. * @return array
  1158. */
  1159. protected function getParseNameData($module, $name, $table, $type)
  1160. {
  1161. $arr = [];
  1162. if (!$name) {
  1163. $parseName = Loader::parseName($table, 1);
  1164. $parseArr = [$table];
  1165. } else {
  1166. $name = str_replace(['.', '/', '\\'], '/', $name);
  1167. $arr = explode('/', $name);
  1168. $parseName = ucfirst(array_pop($arr));
  1169. $parseArr = $arr;
  1170. array_push($parseArr, $parseName);
  1171. }
  1172. //类名不能为内部关键字
  1173. if (in_array(strtolower($parseName), $this->internalKeywords)) {
  1174. throw new Exception('Unable to use internal variable:' . $parseName);
  1175. }
  1176. $appNamespace = Config::get('app_namespace');
  1177. $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
  1178. $moduleDir = APP_PATH . $module . DS;
  1179. $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  1180. return [$parseNamespace, $parseName, $parseFile, $parseArr];
  1181. }
  1182. /**
  1183. * 写入到文件
  1184. * @param string $name
  1185. * @param array $data
  1186. * @param string $pathname
  1187. * @return mixed
  1188. */
  1189. protected function writeToFile($name, $data, $pathname)
  1190. {
  1191. foreach ($data as $index => &$datum) {
  1192. $datum = is_array($datum) ? '' : $datum;
  1193. }
  1194. unset($datum);
  1195. $content = $this->getReplacedStub($name, $data);
  1196. if (!is_dir(dirname($pathname))) {
  1197. mkdir(dirname($pathname), 0755, true);
  1198. }
  1199. return file_put_contents($pathname, $content);
  1200. }
  1201. /**
  1202. * 获取替换后的数据
  1203. * @param string $name
  1204. * @param array $data
  1205. * @return string
  1206. */
  1207. protected function getReplacedStub($name, $data)
  1208. {
  1209. foreach ($data as $index => &$datum) {
  1210. $datum = is_array($datum) ? '' : $datum;
  1211. }
  1212. unset($datum);
  1213. $search = $replace = [];
  1214. foreach ($data as $k => $v) {
  1215. $search[] = "{%{$k}%}";
  1216. $replace[] = $v;
  1217. }
  1218. $stubname = $this->getStub($name);
  1219. if (isset($this->stubList[$stubname])) {
  1220. $stub = $this->stubList[$stubname];
  1221. } else {
  1222. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  1223. }
  1224. $content = str_replace($search, $replace, $stub);
  1225. return $content;
  1226. }
  1227. /**
  1228. * 获取基础模板
  1229. * @param string $name
  1230. * @return string
  1231. */
  1232. protected function getStub($name)
  1233. {
  1234. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  1235. }
  1236. protected function getLangItem($field, $content)
  1237. {
  1238. if ($content || !Lang::has($field)) {
  1239. $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
  1240. $content = str_replace(',', ',', $content);
  1241. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
  1242. list($fieldLang, $item) = explode(':', $content);
  1243. $itemArr = [$field => $fieldLang];
  1244. foreach (explode(',', $item) as $k => $v) {
  1245. $valArr = explode('=', $v);
  1246. if (count($valArr) == 2) {
  1247. list($key, $value) = $valArr;
  1248. $itemArr[$field . ' ' . $key] = $value;
  1249. $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
  1250. }
  1251. }
  1252. } else {
  1253. $itemArr = [$field => $content];
  1254. }
  1255. $resultArr = [];
  1256. foreach ($itemArr as $k => $v) {
  1257. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  1258. }
  1259. return implode(",\n", $resultArr);
  1260. } else {
  1261. return '';
  1262. }
  1263. }
  1264. /**
  1265. * 读取数据和语言数组列表
  1266. * @param array $arr
  1267. * @param boolean $withTpl
  1268. * @return array
  1269. */
  1270. protected function getLangArray($arr, $withTpl = true)
  1271. {
  1272. $langArr = [];
  1273. foreach ($arr as $k => $v) {
  1274. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  1275. }
  1276. return $langArr;
  1277. }
  1278. /**
  1279. * 将数据转换成带字符串
  1280. * @param array $arr
  1281. * @return string
  1282. */
  1283. protected function getArrayString($arr)
  1284. {
  1285. if (!is_array($arr)) {
  1286. return $arr;
  1287. }
  1288. $stringArr = [];
  1289. foreach ($arr as $k => $v) {
  1290. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  1291. if (!$is_var) {
  1292. $v = str_replace("'", "\'", $v);
  1293. $k = str_replace("'", "\'", $k);
  1294. }
  1295. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  1296. }
  1297. return implode(", ", $stringArr);
  1298. }
  1299. protected function getItemArray($item, $field, $comment)
  1300. {
  1301. $itemArr = [];
  1302. $comment = str_replace(',', ',', $comment);
  1303. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  1304. list($fieldLang, $item) = explode(':', $comment);
  1305. $itemArr = [];
  1306. foreach (explode(',', $item) as $k => $v) {
  1307. $valArr = explode('=', $v);
  1308. if (count($valArr) == 2) {
  1309. list($key, $value) = $valArr;
  1310. $itemArr[$key] = $field . ' ' . $key;
  1311. }
  1312. }
  1313. } else {
  1314. foreach ($item as $k => $v) {
  1315. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  1316. }
  1317. }
  1318. return $itemArr;
  1319. }
  1320. protected function getFieldType(& $v)
  1321. {
  1322. $inputType = 'text';
  1323. switch ($v['DATA_TYPE']) {
  1324. case 'bigint':
  1325. case 'int':
  1326. case 'mediumint':
  1327. case 'smallint':
  1328. case 'tinyint':
  1329. $inputType = 'number';
  1330. break;
  1331. case 'enum':
  1332. case 'set':
  1333. $inputType = 'select';
  1334. break;
  1335. case 'decimal':
  1336. case 'double':
  1337. case 'float':
  1338. $inputType = 'number';
  1339. break;
  1340. case 'longtext':
  1341. case 'text':
  1342. case 'mediumtext':
  1343. case 'smalltext':
  1344. case 'tinytext':
  1345. $inputType = 'textarea';
  1346. break;
  1347. case 'year':
  1348. case 'date':
  1349. case 'time':
  1350. case 'datetime':
  1351. case 'timestamp':
  1352. $inputType = 'datetime';
  1353. break;
  1354. default:
  1355. break;
  1356. }
  1357. $fieldsName = $v['COLUMN_NAME'];
  1358. // 指定后缀说明也是个时间字段
  1359. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  1360. $inputType = 'datetime';
  1361. }
  1362. // 指定后缀结尾且类型为enum,说明是个单选框
  1363. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  1364. $inputType = "radio";
  1365. }
  1366. // 指定后缀结尾且类型为set,说明是个复选框
  1367. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  1368. $inputType = "checkbox";
  1369. }
  1370. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1371. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1372. $inputType = "switch";
  1373. }
  1374. // 指定后缀结尾城市选择框
  1375. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1376. $inputType = "citypicker";
  1377. }
  1378. // 指定后缀结尾城市选择框
  1379. if ($this->isMatchSuffix($fieldsName, $this->rangeSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1380. $inputType = "datetimerange";
  1381. }
  1382. // 指定后缀结尾JSON配置
  1383. if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1384. $inputType = "fieldlist";
  1385. }
  1386. // 指定后缀结尾标签配置
  1387. if ($this->isMatchSuffix($fieldsName, $this->tagSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1388. $inputType = "tagsinput";
  1389. }
  1390. return $inputType;
  1391. }
  1392. /**
  1393. * 判断是否符合指定后缀
  1394. * @param string $field 字段名称
  1395. * @param mixed $suffixArr 后缀
  1396. * @return boolean
  1397. */
  1398. protected function isMatchSuffix($field, $suffixArr)
  1399. {
  1400. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1401. foreach ($suffixArr as $k => $v) {
  1402. if (preg_match("/{$v}$/i", $field)) {
  1403. return true;
  1404. }
  1405. }
  1406. return false;
  1407. }
  1408. /**
  1409. * 获取表单分组数据
  1410. * @param string $field
  1411. * @param string $content
  1412. * @return string
  1413. */
  1414. protected function getFormGroup($field, $content)
  1415. {
  1416. $langField = mb_ucfirst($field);
  1417. return <<<EOD
  1418. <div class="form-group">
  1419. <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1420. <div class="col-xs-12 col-sm-8">
  1421. {$content}
  1422. </div>
  1423. </div>
  1424. EOD;
  1425. }
  1426. /**
  1427. * 获取图片模板数据
  1428. * @param string $field
  1429. * @param string $content
  1430. * @return string
  1431. */
  1432. protected function getImageUpload($field, $content)
  1433. {
  1434. $uploadfilter = $selectfilter = '';
  1435. if ($this->isMatchSuffix($field, $this->imageField)) {
  1436. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1437. $selectfilter = ' data-mimetype="image/*"';
  1438. }
  1439. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1440. $preview = ' data-preview-id="p-' . $field . '"';
  1441. $previewcontainer = $preview ? '<ul class="row list-inline faupload-preview" id="p-' . $field . '"></ul>' : '';
  1442. return <<<EOD
  1443. <div class="input-group">
  1444. {$content}
  1445. <div class="input-group-addon no-border no-padding">
  1446. <span><button type="button" id="faupload-{$field}" class="btn btn-danger faupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  1447. <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>
  1448. </div>
  1449. <span class="msg-box n-right" for="c-{$field}"></span>
  1450. </div>
  1451. {$previewcontainer}
  1452. EOD;
  1453. }
  1454. /**
  1455. * 获取JS列数据
  1456. * @param string $field
  1457. * @param string $datatype
  1458. * @param string $extend
  1459. * @param array $itemArr
  1460. * @return string
  1461. */
  1462. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1463. {
  1464. $lang = mb_ucfirst($field);
  1465. $formatter = '';
  1466. foreach ($this->fieldFormatterSuffix as $k => $v) {
  1467. if (preg_match("/{$k}$/i", $field)) {
  1468. if (is_array($v)) {
  1469. if (in_array($datatype, $v['type'])) {
  1470. $formatter = $v['name'];
  1471. break;
  1472. }
  1473. } else {
  1474. $formatter = $v;
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  1480. if ($datatype == 'set') {
  1481. $formatter = 'label';
  1482. }
  1483. foreach ($itemArr as $k => &$v) {
  1484. if (substr($v, 0, 3) !== '__(') {
  1485. $v = "__('" . mb_ucfirst($v) . "')";
  1486. }
  1487. }
  1488. unset($v);
  1489. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
  1490. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1491. if ($itemArr) {
  1492. $html .= ", searchList: " . $searchList;
  1493. }
  1494. // 文件、图片、权重等字段默认不加入搜索栏,字符串类型默认LIKE
  1495. $noSearchFiles = ['file$', 'files$', 'image$', 'images$', '^weigh$'];
  1496. if (preg_match("/" . implode('|', $noSearchFiles) . "/i", $field)) {
  1497. $html .= ", operate: false";
  1498. } else if (in_array($datatype, ['varchar'])) {
  1499. $html .= ", operate: 'LIKE'";
  1500. }
  1501. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1502. $html .= ", operate:'RANGE', addclass:'datetimerange', autocomplete:false";
  1503. } elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
  1504. $html .= ", operate:'BETWEEN'";
  1505. }
  1506. if (in_array($datatype, ['set'])) {
  1507. $html .= ", operate:'FIND_IN_SET'";
  1508. }
  1509. if (in_array($formatter, ['image', 'images'])) {
  1510. $html .= ", events: Table.api.events.image";
  1511. }
  1512. if (in_array($formatter, ['toggle'])) {
  1513. $html .= ", table: table";
  1514. }
  1515. if ($itemArr && !$formatter) {
  1516. $formatter = 'normal';
  1517. }
  1518. if ($formatter) {
  1519. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1520. } else {
  1521. $html .= "}";
  1522. }
  1523. return $html;
  1524. }
  1525. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1526. {
  1527. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1528. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1529. }
  1530. protected function getFieldListName($field)
  1531. {
  1532. return $this->getCamelizeName($field) . 'List';
  1533. }
  1534. }