Crud.php 80 KB

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