Crud.php 78 KB

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