Crud.php 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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. $priKeyArr = [];
  578. $relationPrimaryKey = '';
  579. foreach ($columnList as $k => $v) {
  580. if ($v['COLUMN_KEY'] == 'PRI') {
  581. $priKeyArr[] = $v['COLUMN_NAME'];
  582. }
  583. }
  584. if (!$priKeyArr) {
  585. throw new Exception('Primary key not found!');
  586. }
  587. if (count($priKeyArr) > 1) {
  588. throw new Exception('Multiple primary key not support!');
  589. }
  590. $priKey = reset($priKeyArr);
  591. $order = $priKey;
  592. //如果是关联模型
  593. foreach ($relations as $index => &$relation) {
  594. if ($relation['relationMode'] == 'hasone') {
  595. $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : $table . "_id";
  596. $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  597. if (!in_array($relationForeignKey, $relation['relationFieldList'])) {
  598. throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationForeignKey . ']');
  599. }
  600. if (!in_array($relationPrimaryKey, $fieldArr)) {
  601. throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationPrimaryKey . ']');
  602. }
  603. } else {
  604. $relationForeignKey = $relation['relationForeignKey'] ? $relation['relationForeignKey'] : Loader::parseName($relation['relationName']) . "_id";
  605. $relationPrimaryKey = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $relation['relationPriKey'];
  606. if (!in_array($relationForeignKey, $fieldArr)) {
  607. throw new Exception('table [' . $modelTableName . '] must be contain field [' . $relationForeignKey . ']');
  608. }
  609. if (!in_array($relationPrimaryKey, $relation['relationFieldList'])) {
  610. throw new Exception('relation table [' . $relation['relationTableName'] . '] must be contain field [' . $relationPrimaryKey . ']');
  611. }
  612. }
  613. $relation['relationForeignKey'] = $relationForeignKey;
  614. $relation['relationPrimaryKey'] = $relationPrimaryKey;
  615. $relation['relationClassName'] = $modelNamespace != $relation['relationNamespace'] ? $relation['relationNamespace'] . '\\' . $relation['relationName'] : $relation['relationName'];
  616. }
  617. unset($relation);
  618. try {
  619. Form::setEscapeHtml(false);
  620. $setAttrArr = [];
  621. $getAttrArr = [];
  622. $getEnumArr = [];
  623. $appendAttrList = [];
  624. $controllerAssignList = [];
  625. $headingHtml = '{:build_heading()}';
  626. $recyclebinHtml = '';
  627. //循环所有字段,开始构造视图的HTML和JS信息
  628. foreach ($columnList as $k => $v) {
  629. $field = $v['COLUMN_NAME'];
  630. $itemArr = [];
  631. // 这里构建Enum和Set类型的列表数据
  632. if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
  633. if ($v['DATA_TYPE'] !== 'tinyint') {
  634. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  635. $itemArr = explode(',', str_replace("'", '', $itemArr));
  636. }
  637. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  638. //如果类型为tinyint且有使用备注数据
  639. if ($itemArr && $v['DATA_TYPE'] == 'tinyint') {
  640. $v['DATA_TYPE'] = 'enum';
  641. }
  642. }
  643. // 语言列表
  644. if ($v['COLUMN_COMMENT'] != '') {
  645. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  646. }
  647. $inputType = '';
  648. //保留字段不能修改和添加
  649. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields)) {
  650. $inputType = $this->getFieldType($v);
  651. // 如果是number类型时增加一个步长
  652. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  653. $attrArr = ['id' => "c-{$field}"];
  654. $cssClassArr = ['form-control'];
  655. $fieldName = "row[{$field}]";
  656. $defaultValue = $v['COLUMN_DEFAULT'];
  657. $editValue = "{\$row.{$field}|htmlentities}";
  658. // 如果默认值非null,则是一个必选项
  659. if ($v['IS_NULLABLE'] == 'NO') {
  660. $attrArr['data-rule'] = 'required';
  661. }
  662. //如果字段类型为无符号型,则设置<input min=0>
  663. if (stripos($v['COLUMN_TYPE'], 'unsigned') !== false) {
  664. $attrArr['min'] = 0;
  665. }
  666. if ($inputType == 'select') {
  667. $cssClassArr[] = 'selectpicker';
  668. $attrArr['class'] = implode(' ', $cssClassArr);
  669. if ($v['DATA_TYPE'] == 'set') {
  670. $attrArr['multiple'] = '';
  671. $fieldName .= "[]";
  672. }
  673. $attrArr['name'] = $fieldName;
  674. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  675. $itemArr = $this->getLangArray($itemArr, false);
  676. //添加一个获取器
  677. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  678. if ($v['DATA_TYPE'] == 'set') {
  679. $this->setAttr($setAttrArr, $field, $inputType);
  680. }
  681. $this->appendAttr($appendAttrList, $field);
  682. $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  683. $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  684. } elseif ($inputType == 'datetime') {
  685. $cssClassArr[] = 'datetimepicker';
  686. $attrArr['class'] = implode(' ', $cssClassArr);
  687. $format = "YYYY-MM-DD HH:mm:ss";
  688. $phpFormat = "Y-m-d H:i:s";
  689. $fieldFunc = '';
  690. switch ($v['DATA_TYPE']) {
  691. case 'year':
  692. $format = "YYYY";
  693. $phpFormat = 'Y';
  694. break;
  695. case 'date':
  696. $format = "YYYY-MM-DD";
  697. $phpFormat = 'Y-m-d';
  698. break;
  699. case 'time':
  700. $format = "HH:mm:ss";
  701. $phpFormat = 'H:i:s';
  702. break;
  703. case 'timestamp':
  704. $fieldFunc = 'datetime';
  705. // no break
  706. case 'datetime':
  707. $format = "YYYY-MM-DD HH:mm:ss";
  708. $phpFormat = 'Y-m-d H:i:s';
  709. break;
  710. default:
  711. $fieldFunc = 'datetime';
  712. $this->getAttr($getAttrArr, $field, $inputType);
  713. $this->setAttr($setAttrArr, $field, $inputType);
  714. $this->appendAttr($appendAttrList, $field);
  715. break;
  716. }
  717. $defaultDateTime = "{:date('{$phpFormat}')}";
  718. $attrArr['data-date-format'] = $format;
  719. $attrArr['data-use-current'] = "true";
  720. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  721. $formEditElement = Form::text($fieldName, ($fieldFunc ? "{:\$row.{$field}?{$fieldFunc}(\$row.{$field}):''}" : "{\$row.{$field}{$fieldFunc}}"), $attrArr);
  722. } elseif ($inputType == 'datetimerange') {
  723. $cssClassArr[] = 'datetimerange';
  724. $attrArr['class'] = implode(' ', $cssClassArr);
  725. $attrArr['data-locale'] = '{"format":"YYYY-MM-DD HH:mm:ss"}';
  726. $fieldFunc = '';
  727. $defaultDateTime = "";
  728. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  729. $formEditElement = Form::text($fieldName, $editValue, $attrArr);
  730. } elseif ($inputType == 'checkbox' || $inputType == 'radio') {
  731. unset($attrArr['data-rule']);
  732. $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
  733. $attrArr['name'] = "row[{$fieldName}]";
  734. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
  735. $itemArr = $this->getLangArray($itemArr, false);
  736. //添加一个获取器
  737. $this->getAttr($getAttrArr, $field, $inputType);
  738. if ($inputType == 'checkbox') {
  739. $this->setAttr($setAttrArr, $field, $inputType);
  740. }
  741. $this->appendAttr($appendAttrList, $field);
  742. $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
  743. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  744. $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  745. } elseif ($inputType == 'textarea' && !$this->isMatchSuffix($field, $this->selectpagesSuffix) && !$this->isMatchSuffix($field, $this->imageField)) {
  746. $cssClassArr[] = $this->isMatchSuffix($field, $this->editorSuffix) ? $this->editorClass : '';
  747. $attrArr['class'] = implode(' ', $cssClassArr);
  748. $attrArr['rows'] = 5;
  749. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  750. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  751. } elseif ($inputType == 'switch') {
  752. unset($attrArr['data-rule']);
  753. if ($defaultValue === '1' || $defaultValue === 'Y') {
  754. $yes = $defaultValue;
  755. $no = $defaultValue === '1' ? '0' : 'N';
  756. } else {
  757. $no = $defaultValue;
  758. $yes = $defaultValue === '0' ? '1' : 'Y';
  759. }
  760. if (!$itemArr) {
  761. $itemArr = [$yes => 'Yes', $no => 'No'];
  762. }
  763. $stateNoClass = 'fa-flip-horizontal text-gray';
  764. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
  765. $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}"]);
  766. } elseif ($inputType == 'citypicker') {
  767. $attrArr['class'] = implode(' ', $cssClassArr);
  768. $attrArr['data-toggle'] = "city-picker";
  769. $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
  770. $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
  771. } elseif ($inputType == 'tagsinput') {
  772. $attrArr['class'] = implode(' ', $cssClassArr);
  773. $attrArr['data-role'] = "tagsinput";
  774. $formAddElement = Form::input('text', $fieldName, $defaultValue, $attrArr);
  775. $formEditElement = Form::input('text', $fieldName, $editValue, $attrArr);
  776. } elseif ($inputType == 'fieldlist') {
  777. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  778. $templateName = !isset($itemArr['key']) && !isset($itemArr['value']) && count($itemArr) > 0 ? 'fieldlist-template' : 'fieldlist';
  779. $itemKey = isset($itemArr['key']) ? ucfirst($itemArr['key']) : 'Key';
  780. $itemValue = isset($itemArr['value']) ? ucfirst($itemArr['value']) : 'Value';
  781. $theadListArr = $tbodyListArr = [];
  782. foreach ($itemArr as $index => $item) {
  783. $theadListArr[] = "<td>{:__('" . $item . "')}</td>";
  784. $tbodyListArr[] = '<td><input type="text" name="<%=name%>[<%=index%>][' . $index . ']" class="form-control" value="<%=row.' . $index . '%>"/></td>';
  785. }
  786. $colspan = count($theadListArr) + 1;
  787. $commonFields = ['field' => $field, 'fieldName' => $fieldName, 'itemKey' => $itemKey, 'itemValue' => $itemValue, 'theadList' => implode("\n", $theadListArr), 'tbodyList' => implode("\n", $tbodyListArr), 'colspan' => $colspan];
  788. $formAddElement = $this->getReplacedStub('html/' . $templateName, array_merge($commonFields, ['fieldValue' => $defaultValue]));
  789. $formEditElement = $this->getReplacedStub('html/' . $templateName, array_merge($commonFields, ['fieldValue' => $editValue]));
  790. } else {
  791. $search = $replace = '';
  792. //特殊字段为关联搜索
  793. if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
  794. $inputType = 'text';
  795. $defaultValue = '';
  796. $attrArr['data-rule'] = 'required';
  797. $cssClassArr[] = 'selectpage';
  798. $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
  799. $attrArr['data-source'] = $selectpageController . "/index";
  800. //如果是类型表需要特殊处理下
  801. if ($selectpageController == 'category') {
  802. $attrArr['data-source'] = 'category/selectpage';
  803. $attrArr['data-params'] = '##replacetext##';
  804. $search = '"##replacetext##"';
  805. $replace = '\'{"custom[type]":"' . $table . '"}\'';
  806. } elseif ($selectpageController == 'admin') {
  807. $attrArr['data-source'] = 'auth/admin/selectpage';
  808. } elseif ($selectpageController == 'user') {
  809. $attrArr['data-source'] = 'user/user/index';
  810. }
  811. if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
  812. $attrArr['data-multiple'] = 'true';
  813. }
  814. foreach ($this->fieldSelectpageMap as $m => $n) {
  815. if (in_array($field, $n)) {
  816. $attrArr['data-field'] = $m;
  817. break;
  818. }
  819. }
  820. }
  821. //因为有自动完成可输入其它内容
  822. $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  823. $attrArr['class'] = implode(' ', $cssClassArr);
  824. $isUpload = false;
  825. if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
  826. $isUpload = true;
  827. }
  828. //如果是步长则加上步长
  829. if ($step) {
  830. $attrArr['step'] = $step;
  831. }
  832. //如果是图片加上个size
  833. if ($isUpload) {
  834. $attrArr['size'] = 50;
  835. }
  836. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  837. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  838. if ($search && $replace) {
  839. $formAddElement = str_replace($search, $replace, $formAddElement);
  840. $formEditElement = str_replace($search, $replace, $formEditElement);
  841. }
  842. //如果是图片或文件
  843. if ($isUpload) {
  844. $formAddElement = $this->getImageUpload($field, $formAddElement);
  845. $formEditElement = $this->getImageUpload($field, $formEditElement);
  846. }
  847. }
  848. //构造添加和编辑HTML信息
  849. $addList[] = $this->getFormGroup($field, $formAddElement);
  850. $editList[] = $this->getFormGroup($field, $formEditElement);
  851. }
  852. //过滤text类型字段
  853. if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
  854. //主键
  855. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
  856. $priDefined = true;
  857. $javascriptList[] = "{checkbox: true}";
  858. }
  859. if ($this->deleteTimeField == $field) {
  860. $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
  861. continue;
  862. }
  863. if (!$fields || in_array($field, explode(',', $fields))) {
  864. //构造JS列信息
  865. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  866. }
  867. if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
  868. $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
  869. }
  870. //排序方式,如果有指定排序字段,否则按主键排序
  871. $order = $field == $this->sortField ? $this->sortField : $order;
  872. }
  873. }
  874. //循环关联表,追加语言包和JS列
  875. foreach ($relations as $index => $relation) {
  876. foreach ($relation['relationColumnList'] as $k => $v) {
  877. // 不显示的字段直接过滤掉
  878. if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  879. continue;
  880. }
  881. $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  882. // 语言列表
  883. if ($v['COLUMN_COMMENT'] != '') {
  884. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  885. }
  886. //过滤text类型字段
  887. if ($v['DATA_TYPE'] != 'text') {
  888. //构造JS列信息
  889. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  890. }
  891. }
  892. }
  893. //JS最后一列加上操作列
  894. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  895. $addList = implode("\n", array_filter($addList));
  896. $editList = implode("\n", array_filter($editList));
  897. $javascriptList = implode(",\n", array_filter($javascriptList));
  898. $langList = implode(",\n", array_filter($langList));
  899. //数组等号对齐
  900. $langList = array_filter(explode(",\n", $langList . ",\n"));
  901. foreach ($langList as &$line) {
  902. if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
  903. $line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
  904. }
  905. }
  906. unset($line);
  907. $langList = implode(",\n", array_filter($langList));
  908. $fixedcolumns = count($columnList) >= 10 ? 1 : $fixedcolumns;
  909. $fixedColumnsJs = '';
  910. if (is_numeric($fixedcolumns) && $fixedcolumns) {
  911. $fixedColumnsJs = "\n" . str_repeat(" ", 16) . "fixedColumns: true,\n" . str_repeat(" ", 16) . ($fixedcolumns < 0 ? "fixedNumber" : "fixedRightNumber") . ": " . $fixedcolumns . ",";
  912. }
  913. //表注释
  914. $tableComment = $modelTableInfo['Comment'];
  915. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  916. $modelInit = '';
  917. if ($priKey != $order) {
  918. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  919. }
  920. $data = [
  921. 'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';",
  922. 'controllerNamespace' => $controllerNamespace,
  923. 'modelNamespace' => $modelNamespace,
  924. 'validateNamespace' => $validateNamespace,
  925. 'controllerUrl' => $controllerUrl,
  926. 'controllerName' => $controllerName,
  927. 'controllerAssignList' => implode("\n", $controllerAssignList),
  928. 'modelName' => $modelName,
  929. 'modelTableName' => $modelTableName,
  930. 'modelTableType' => $modelTableType,
  931. 'modelTableTypeName' => $modelTableTypeName,
  932. 'validateName' => $validateName,
  933. 'tableComment' => $tableComment,
  934. 'iconName' => $iconName,
  935. 'pk' => $priKey,
  936. 'order' => $order,
  937. 'fixedColumnsJs' => $fixedColumnsJs,
  938. 'table' => $table,
  939. 'tableName' => $modelTableName,
  940. 'addList' => $addList,
  941. 'editList' => $editList,
  942. 'javascriptList' => $javascriptList,
  943. 'langList' => $langList,
  944. 'softDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
  945. 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  946. 'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'int'" : 'false',
  947. 'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
  948. 'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
  949. 'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
  950. 'relationSearch' => $relations ? 'true' : 'false',
  951. 'relationWithList' => '',
  952. 'relationMethodList' => '',
  953. 'controllerIndex' => '',
  954. 'recyclebinJs' => '',
  955. 'headingHtml' => $headingHtml,
  956. 'recyclebinHtml' => $recyclebinHtml,
  957. 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(in_array($priKey, explode(',', $fields)) ? explode(',', $fields) : explode(',', $priKey . ',' . $fields))) . "']);" : '',
  958. 'appendAttrList' => implode(",\n", $appendAttrList),
  959. 'getEnumList' => implode("\n\n", $getEnumArr),
  960. 'getAttrList' => implode("\n\n", $getAttrArr),
  961. 'setAttrList' => implode("\n\n", $setAttrArr),
  962. 'modelInit' => $modelInit,
  963. ];
  964. //如果使用关联模型
  965. if ($relations) {
  966. $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  967. foreach ($relations as $index => $relation) {
  968. //需要构造关联的方法
  969. $relation['relationMethod'] = strtolower($relation['relationName']);
  970. //关联的模式
  971. $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
  972. //关联字段
  973. $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  974. //预载入的方法
  975. $relationWithList[] = $relation['relationMethod'];
  976. unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  977. //构造关联模型的方法
  978. $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
  979. //如果设置了显示主表字段,则必须显式将关联表字段显示
  980. if ($fields) {
  981. $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
  982. }
  983. //显示的字段
  984. if ($relation['relationFields']) {
  985. $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  986. }
  987. }
  988. $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  989. $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  990. $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  991. //需要重写index方法
  992. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  993. } elseif ($fields) {
  994. $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  995. //需要重写index方法
  996. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  997. }
  998. // 生成控制器文件
  999. $this->writeToFile('controller', $data, $controllerFile);
  1000. // 生成模型文件
  1001. $this->writeToFile('model', $data, $modelFile);
  1002. if ($relations) {
  1003. foreach ($relations as $i => $relation) {
  1004. $relation['modelNamespace'] = $relation['relationNamespace'];
  1005. if (!is_file($relation['relationFile'])) {
  1006. // 生成关联模型文件
  1007. $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  1008. }
  1009. }
  1010. }
  1011. // 生成验证文件
  1012. $this->writeToFile('validate', $data, $validateFile);
  1013. // 生成视图文件
  1014. $this->writeToFile('add', $data, $addFile);
  1015. $this->writeToFile('edit', $data, $editFile);
  1016. $this->writeToFile('index', $data, $indexFile);
  1017. if ($recyclebinHtml) {
  1018. $this->writeToFile('recyclebin', $data, $recyclebinFile);
  1019. $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
  1020. $recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
  1021. $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['deleteTimeField' => $this->deleteTimeField, 'recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
  1022. }
  1023. // 生成JS文件
  1024. $this->writeToFile('javascript', $data, $javascriptFile);
  1025. // 生成语言文件
  1026. $this->writeToFile('lang', $data, $langFile);
  1027. } catch (ErrorException $e) {
  1028. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  1029. }
  1030. //继续生成菜单
  1031. if ($menu) {
  1032. exec("php think menu -c {$controllerUrl}");
  1033. }
  1034. $output->info("Build Successed");
  1035. }
  1036. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  1037. {
  1038. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1039. return;
  1040. }
  1041. $fieldList = $this->getFieldListName($field);
  1042. $methodName = 'get' . ucfirst($fieldList);
  1043. foreach ($itemArr as $k => &$v) {
  1044. $v = "__('" . mb_ucfirst($v) . "')";
  1045. }
  1046. unset($v);
  1047. $itemString = $this->getArrayString($itemArr);
  1048. $getEnum[] = <<<EOD
  1049. public function {$methodName}()
  1050. {
  1051. return [{$itemString}];
  1052. }
  1053. EOD;
  1054. $controllerAssignList[] = <<<EOD
  1055. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  1056. EOD;
  1057. }
  1058. protected function getAttr(&$getAttr, $field, $inputType = '')
  1059. {
  1060. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1061. return;
  1062. }
  1063. $attrField = ucfirst($this->getCamelizeName($field));
  1064. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  1065. }
  1066. protected function setAttr(&$setAttr, $field, $inputType = '')
  1067. {
  1068. if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
  1069. return;
  1070. }
  1071. $attrField = ucfirst($this->getCamelizeName($field));
  1072. if ($inputType == 'datetime') {
  1073. $return = <<<EOD
  1074. return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  1075. EOD;
  1076. } elseif (in_array($inputType, ['checkbox', 'select'])) {
  1077. $return = <<<EOD
  1078. return is_array(\$value) ? implode(',', \$value) : \$value;
  1079. EOD;
  1080. }
  1081. $setAttr[] = <<<EOD
  1082. protected function set{$attrField}Attr(\$value)
  1083. {
  1084. $return
  1085. }
  1086. EOD;
  1087. }
  1088. protected function appendAttr(&$appendAttrList, $field)
  1089. {
  1090. $appendAttrList[] = <<<EOD
  1091. '{$field}_text'
  1092. EOD;
  1093. }
  1094. /**
  1095. * 移除相对的空目录
  1096. * @param $parseFile
  1097. * @param $parseArr
  1098. * @return bool
  1099. */
  1100. protected function removeEmptyBaseDir($parseFile, $parseArr)
  1101. {
  1102. if (count($parseArr) > 1) {
  1103. $parentDir = dirname($parseFile);
  1104. for ($i = 0; $i < count($parseArr); $i++) {
  1105. try {
  1106. $iterator = new \FilesystemIterator($parentDir);
  1107. $isDirEmpty = !$iterator->valid();
  1108. if ($isDirEmpty) {
  1109. rmdir($parentDir);
  1110. $parentDir = dirname($parentDir);
  1111. } else {
  1112. return true;
  1113. }
  1114. } catch (\UnexpectedValueException $e) {
  1115. return false;
  1116. }
  1117. }
  1118. }
  1119. return true;
  1120. }
  1121. /**
  1122. * 获取控制器相关信息
  1123. * @param $module
  1124. * @param $controller
  1125. * @param $table
  1126. * @return array
  1127. */
  1128. protected function getControllerData($module, $controller, $table)
  1129. {
  1130. return $this->getParseNameData($module, $controller, $table, 'controller');
  1131. }
  1132. /**
  1133. * 获取模型相关信息
  1134. * @param $module
  1135. * @param $model
  1136. * @param $table
  1137. * @return array
  1138. */
  1139. protected function getModelData($module, $model, $table)
  1140. {
  1141. return $this->getParseNameData($module, $model, $table, 'model');
  1142. }
  1143. /**
  1144. * 获取验证器相关信息
  1145. * @param $module
  1146. * @param $validate
  1147. * @param $table
  1148. * @return array
  1149. */
  1150. protected function getValidateData($module, $validate, $table)
  1151. {
  1152. return $this->getParseNameData($module, $validate, $table, 'validate');
  1153. }
  1154. /**
  1155. * 获取已解析相关信息
  1156. * @param string $module 模块名称
  1157. * @param string $name 自定义名称
  1158. * @param string $table 数据表名
  1159. * @param string $type 解析类型,本例中为controller、model、validate
  1160. * @return array
  1161. */
  1162. protected function getParseNameData($module, $name, $table, $type)
  1163. {
  1164. $arr = [];
  1165. if (!$name) {
  1166. $parseName = Loader::parseName($table, 1);
  1167. $parseArr = [$table];
  1168. } else {
  1169. $name = str_replace(['.', '/', '\\'], '/', $name);
  1170. $arr = explode('/', $name);
  1171. $parseName = ucfirst(array_pop($arr));
  1172. $parseArr = $arr;
  1173. array_push($parseArr, $parseName);
  1174. }
  1175. //类名不能为内部关键字
  1176. if (in_array(strtolower($parseName), $this->internalKeywords)) {
  1177. throw new Exception('Unable to use internal variable:' . $parseName);
  1178. }
  1179. $appNamespace = Config::get('app_namespace');
  1180. $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
  1181. $moduleDir = APP_PATH . $module . DS;
  1182. $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  1183. return [$parseNamespace, $parseName, $parseFile, $parseArr];
  1184. }
  1185. /**
  1186. * 写入到文件
  1187. * @param string $name
  1188. * @param array $data
  1189. * @param string $pathname
  1190. * @return mixed
  1191. */
  1192. protected function writeToFile($name, $data, $pathname)
  1193. {
  1194. foreach ($data as $index => &$datum) {
  1195. $datum = is_array($datum) ? '' : $datum;
  1196. }
  1197. unset($datum);
  1198. $content = $this->getReplacedStub($name, $data);
  1199. if (!is_dir(dirname($pathname))) {
  1200. mkdir(dirname($pathname), 0755, true);
  1201. }
  1202. return file_put_contents($pathname, $content);
  1203. }
  1204. /**
  1205. * 获取替换后的数据
  1206. * @param string $name
  1207. * @param array $data
  1208. * @return string
  1209. */
  1210. protected function getReplacedStub($name, $data)
  1211. {
  1212. foreach ($data as $index => &$datum) {
  1213. $datum = is_array($datum) ? '' : $datum;
  1214. }
  1215. unset($datum);
  1216. $search = $replace = [];
  1217. foreach ($data as $k => $v) {
  1218. $search[] = "{%{$k}%}";
  1219. $replace[] = $v;
  1220. }
  1221. $stubname = $this->getStub($name);
  1222. if (isset($this->stubList[$stubname])) {
  1223. $stub = $this->stubList[$stubname];
  1224. } else {
  1225. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  1226. }
  1227. $content = str_replace($search, $replace, $stub);
  1228. return $content;
  1229. }
  1230. /**
  1231. * 获取基础模板
  1232. * @param string $name
  1233. * @return string
  1234. */
  1235. protected function getStub($name)
  1236. {
  1237. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  1238. }
  1239. protected function getLangItem($field, $content)
  1240. {
  1241. if ($content || !Lang::has($field)) {
  1242. $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
  1243. $content = str_replace(',', ',', $content);
  1244. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
  1245. list($fieldLang, $item) = explode(':', $content);
  1246. $itemArr = [$field => $fieldLang];
  1247. foreach (explode(',', $item) as $k => $v) {
  1248. $valArr = explode('=', $v);
  1249. if (count($valArr) == 2) {
  1250. list($key, $value) = $valArr;
  1251. $itemArr[$field . ' ' . $key] = $value;
  1252. $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
  1253. }
  1254. }
  1255. } else {
  1256. $itemArr = [$field => $content];
  1257. }
  1258. $resultArr = [];
  1259. foreach ($itemArr as $k => $v) {
  1260. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  1261. }
  1262. return implode(",\n", $resultArr);
  1263. } else {
  1264. return '';
  1265. }
  1266. }
  1267. /**
  1268. * 读取数据和语言数组列表
  1269. * @param array $arr
  1270. * @param boolean $withTpl
  1271. * @return array
  1272. */
  1273. protected function getLangArray($arr, $withTpl = true)
  1274. {
  1275. $langArr = [];
  1276. foreach ($arr as $k => $v) {
  1277. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  1278. }
  1279. return $langArr;
  1280. }
  1281. /**
  1282. * 将数据转换成带字符串
  1283. * @param array $arr
  1284. * @return string
  1285. */
  1286. protected function getArrayString($arr)
  1287. {
  1288. if (!is_array($arr)) {
  1289. return $arr;
  1290. }
  1291. $stringArr = [];
  1292. foreach ($arr as $k => $v) {
  1293. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  1294. if (!$is_var) {
  1295. $v = str_replace("'", "\'", $v);
  1296. $k = str_replace("'", "\'", $k);
  1297. }
  1298. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  1299. }
  1300. return implode(", ", $stringArr);
  1301. }
  1302. protected function getItemArray($item, $field, $comment)
  1303. {
  1304. $itemArr = [];
  1305. $comment = str_replace(',', ',', $comment);
  1306. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  1307. list($fieldLang, $item) = explode(':', $comment);
  1308. $itemArr = [];
  1309. foreach (explode(',', $item) as $k => $v) {
  1310. $valArr = explode('=', $v);
  1311. if (count($valArr) == 2) {
  1312. list($key, $value) = $valArr;
  1313. $itemArr[$key] = $field . ' ' . $key;
  1314. }
  1315. }
  1316. } else {
  1317. foreach ($item as $k => $v) {
  1318. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  1319. }
  1320. }
  1321. return $itemArr;
  1322. }
  1323. protected function getFieldType(& $v)
  1324. {
  1325. $inputType = 'text';
  1326. switch ($v['DATA_TYPE']) {
  1327. case 'bigint':
  1328. case 'int':
  1329. case 'mediumint':
  1330. case 'smallint':
  1331. case 'tinyint':
  1332. $inputType = 'number';
  1333. break;
  1334. case 'enum':
  1335. case 'set':
  1336. $inputType = 'select';
  1337. break;
  1338. case 'decimal':
  1339. case 'double':
  1340. case 'float':
  1341. $inputType = 'number';
  1342. break;
  1343. case 'longtext':
  1344. case 'text':
  1345. case 'mediumtext':
  1346. case 'smalltext':
  1347. case 'tinytext':
  1348. $inputType = 'textarea';
  1349. break;
  1350. case 'year':
  1351. case 'date':
  1352. case 'time':
  1353. case 'datetime':
  1354. case 'timestamp':
  1355. $inputType = 'datetime';
  1356. break;
  1357. default:
  1358. break;
  1359. }
  1360. $fieldsName = $v['COLUMN_NAME'];
  1361. // 指定后缀说明也是个时间字段
  1362. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  1363. $inputType = 'datetime';
  1364. }
  1365. // 指定后缀结尾且类型为enum,说明是个单选框
  1366. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  1367. $inputType = "radio";
  1368. }
  1369. // 指定后缀结尾且类型为set,说明是个复选框
  1370. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  1371. $inputType = "checkbox";
  1372. }
  1373. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1374. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1375. $inputType = "switch";
  1376. }
  1377. // 指定后缀结尾城市选择框
  1378. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1379. $inputType = "citypicker";
  1380. }
  1381. // 指定后缀结尾城市选择框
  1382. if ($this->isMatchSuffix($fieldsName, $this->rangeSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1383. $inputType = "datetimerange";
  1384. }
  1385. // 指定后缀结尾JSON配置
  1386. if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1387. $inputType = "fieldlist";
  1388. }
  1389. // 指定后缀结尾标签配置
  1390. if ($this->isMatchSuffix($fieldsName, $this->tagSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1391. $inputType = "tagsinput";
  1392. }
  1393. return $inputType;
  1394. }
  1395. /**
  1396. * 判断是否符合指定后缀
  1397. * @param string $field 字段名称
  1398. * @param mixed $suffixArr 后缀
  1399. * @return boolean
  1400. */
  1401. protected function isMatchSuffix($field, $suffixArr)
  1402. {
  1403. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1404. foreach ($suffixArr as $k => $v) {
  1405. if (preg_match("/{$v}$/i", $field)) {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. /**
  1412. * 获取表单分组数据
  1413. * @param string $field
  1414. * @param string $content
  1415. * @return string
  1416. */
  1417. protected function getFormGroup($field, $content)
  1418. {
  1419. $langField = mb_ucfirst($field);
  1420. return <<<EOD
  1421. <div class="form-group">
  1422. <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1423. <div class="col-xs-12 col-sm-8">
  1424. {$content}
  1425. </div>
  1426. </div>
  1427. EOD;
  1428. }
  1429. /**
  1430. * 获取图片模板数据
  1431. * @param string $field
  1432. * @param string $content
  1433. * @return string
  1434. */
  1435. protected function getImageUpload($field, $content)
  1436. {
  1437. $uploadfilter = $selectfilter = '';
  1438. if ($this->isMatchSuffix($field, $this->imageField)) {
  1439. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1440. $selectfilter = ' data-mimetype="image/*"';
  1441. }
  1442. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1443. $preview = ' data-preview-id="p-' . $field . '"';
  1444. $previewcontainer = $preview ? '<ul class="row list-inline faupload-preview" id="p-' . $field . '"></ul>' : '';
  1445. return <<<EOD
  1446. <div class="input-group">
  1447. {$content}
  1448. <div class="input-group-addon no-border no-padding">
  1449. <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>
  1450. <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>
  1451. </div>
  1452. <span class="msg-box n-right" for="c-{$field}"></span>
  1453. </div>
  1454. {$previewcontainer}
  1455. EOD;
  1456. }
  1457. /**
  1458. * 获取JS列数据
  1459. * @param string $field
  1460. * @param string $datatype
  1461. * @param string $extend
  1462. * @param array $itemArr
  1463. * @return string
  1464. */
  1465. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1466. {
  1467. $lang = mb_ucfirst($field);
  1468. $formatter = '';
  1469. foreach ($this->fieldFormatterSuffix as $k => $v) {
  1470. if (preg_match("/{$k}$/i", $field)) {
  1471. if (is_array($v)) {
  1472. if (in_array($datatype, $v['type'])) {
  1473. $formatter = $v['name'];
  1474. break;
  1475. }
  1476. } else {
  1477. $formatter = $v;
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  1483. if ($datatype == 'set') {
  1484. $formatter = 'label';
  1485. }
  1486. foreach ($itemArr as $k => &$v) {
  1487. if (substr($v, 0, 3) !== '__(') {
  1488. $v = "__('" . mb_ucfirst($v) . "')";
  1489. }
  1490. }
  1491. unset($v);
  1492. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
  1493. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1494. if ($itemArr) {
  1495. $html .= ", searchList: " . $searchList;
  1496. }
  1497. // 文件、图片、权重等字段默认不加入搜索栏,字符串类型默认LIKE
  1498. $noSearchFiles = ['file$', 'files$', 'image$', 'images$', '^weigh$'];
  1499. if (preg_match("/" . implode('|', $noSearchFiles) . "/i", $field)) {
  1500. $html .= ", operate: false";
  1501. } else if (in_array($datatype, ['varchar'])) {
  1502. $html .= ", operate: 'LIKE'";
  1503. }
  1504. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1505. $html .= ", operate:'RANGE', addclass:'datetimerange', autocomplete:false";
  1506. } elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
  1507. $html .= ", operate:'BETWEEN'";
  1508. }
  1509. if (in_array($datatype, ['set'])) {
  1510. $html .= ", operate:'FIND_IN_SET'";
  1511. }
  1512. if (in_array($formatter, ['image', 'images'])) {
  1513. $html .= ", events: Table.api.events.image";
  1514. }
  1515. if (in_array($formatter, ['toggle'])) {
  1516. $html .= ", table: table";
  1517. }
  1518. if ($itemArr && !$formatter) {
  1519. $formatter = 'normal';
  1520. }
  1521. if ($formatter) {
  1522. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1523. } else {
  1524. $html .= "}";
  1525. }
  1526. return $html;
  1527. }
  1528. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1529. {
  1530. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1531. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1532. }
  1533. protected function getFieldListName($field)
  1534. {
  1535. return $this->getCamelizeName($field) . 'List';
  1536. }
  1537. }