Crud.php 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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. } elseif ($selectpageController == 'user') {
  851. $attrArr['data-source'] = 'user/user/index';
  852. $attrArr['data-field'] = 'nickname';
  853. }
  854. if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
  855. $attrArr['data-multiple'] = 'true';
  856. }
  857. $tableInfo = null;
  858. try {
  859. $tableInfo = \think\Db::name($selectpageTable)->getTableInfo();
  860. if (isset($tableInfo['fields'])) {
  861. foreach ($tableInfo['fields'] as $m => $n) {
  862. if (in_array($n, ['nickname', 'title', 'name'])) {
  863. $selectpageField = $n;
  864. break;
  865. }
  866. }
  867. }
  868. } catch (\Exception $e) {
  869. }
  870. if (!$selectpageField) {
  871. foreach ($this->fieldSelectpageMap as $m => $n) {
  872. if (in_array($field, $n)) {
  873. $attrArr['data-field'] = $m;
  874. break;
  875. }
  876. }
  877. }
  878. }
  879. //因为有自动完成可输入其它内容
  880. $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  881. $attrArr['class'] = implode(' ', $cssClassArr);
  882. $isUpload = false;
  883. if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
  884. $isUpload = true;
  885. }
  886. //如果是步长则加上步长
  887. if ($step) {
  888. $attrArr['step'] = $step;
  889. }
  890. //如果是图片加上个size
  891. if ($isUpload) {
  892. $attrArr['size'] = 50;
  893. }
  894. //字段默认值判断
  895. if ('NULL' == $defaultValue || "''" == $defaultValue) {
  896. $defaultValue = '';
  897. }
  898. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  899. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  900. if ($search && $replace) {
  901. $formAddElement = str_replace($search, $replace, $formAddElement);
  902. $formEditElement = str_replace($search, $replace, $formEditElement);
  903. }
  904. //如果是图片或文件
  905. if ($isUpload) {
  906. $formAddElement = $this->getImageUpload($field, $formAddElement);
  907. $formEditElement = $this->getImageUpload($field, $formEditElement);
  908. }
  909. }
  910. //构造添加和编辑HTML信息
  911. $addList[] = $this->getFormGroup($field, $formAddElement);
  912. $editList[] = $this->getFormGroup($field, $formEditElement);
  913. }
  914. //过滤text类型字段
  915. if ($v['DATA_TYPE'] != 'text' && $inputType != 'fieldlist') {
  916. //主键
  917. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
  918. $priDefined = true;
  919. $javascriptList[] = "{checkbox: true}";
  920. }
  921. if ($this->deleteTimeField == $field) {
  922. $recyclebinHtml = $this->getReplacedStub('html/recyclebin-html', ['controllerUrl' => $controllerUrl]);
  923. continue;
  924. }
  925. if (!$fields || in_array($field, explode(',', $fields))) {
  926. //构造JS列信息
  927. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr, $v);
  928. }
  929. if ($this->headingFilterField && $this->headingFilterField == $field && $itemArr) {
  930. $headingHtml = $this->getReplacedStub('html/heading-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false)]);
  931. $multipleHtml = $this->getReplacedStub('html/multiple-html', ['field' => $field, 'fieldName' => Loader::parseName($field, 1, false), 'controllerUrl' => $controllerUrl]);
  932. }
  933. //排序方式,如果有指定排序字段,否则按主键排序
  934. $order = $field == $this->sortField ? $this->sortField : $order;
  935. }
  936. }
  937. //循环关联表,追加语言包和JS列
  938. foreach ($relations as $index => $relation) {
  939. if ($relation['relationMode'] == 'hasmany') {
  940. $relationFieldText = ucfirst(strtolower($relation['relationName'])) . ' List';
  941. // 语言列表
  942. if ($relation['relationTableInfo']['Comment']) {
  943. $langList[] = $this->getLangItem($relationFieldText, rtrim($relation['relationTableInfo']['Comment'], "表") . "列表");
  944. }
  945. $relationTableName = $relation['relationTableName'];
  946. $relationTableName = stripos($relationTableName, $prefix) === 0 ? substr($relationTableName, strlen($prefix)) : $relationTableName;
  947. list($realtionControllerNamespace, $realtionControllerName, $realtionControllerFile, $realtionControllerArr) = $this->getControllerData($moduleName, $relation['relationController'], $relationTableName);
  948. $realtionControllerArr = array_map("strtolower", $realtionControllerArr);
  949. if (count($realtionControllerArr) > 1) {
  950. $realtionControllerArr = [implode('.', $realtionControllerArr)];
  951. }
  952. $realtionControllerArr[] = 'index';
  953. $realtionControllerArr[] = $relation['relationForeignKey'] . '/{ids}';
  954. $relationControllerUrl = implode('/', $realtionControllerArr);
  955. //构造JS列信息
  956. $operateButtonList[] = "{name: 'addtabs',title: __('{$relationFieldText}'),text: __('{$relationFieldText}'),classname: 'btn btn-xs btn-info btn-dialog',icon: 'fa fa-list',url: '" . $relationControllerUrl . "'}";
  957. //echo "php think crud -t {$relation['relationTableName']} -c {$relation['relationController']} -m {$relation['relationModel']} -i " . implode(',', $relation['relationFields']);
  958. //不存在关联表控制器的情况下才进行生成
  959. if (!is_file($realtionControllerFile)) {
  960. exec("php think crud -t {$relation['relationTableName']} -c {$relation['relationController']} -m {$relation['relationModel']} -i " . implode(',', $relation['relationFields']));
  961. }
  962. }
  963. foreach ($relation['relationColumnList'] as $k => $v) {
  964. // 不显示的字段直接过滤掉
  965. if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  966. continue;
  967. }
  968. $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  969. // 语言列表
  970. if ($v['COLUMN_COMMENT'] != '') {
  971. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  972. }
  973. //过滤text类型字段
  974. if ($v['DATA_TYPE'] != 'text') {
  975. //构造JS列信息
  976. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE'], '', [], $v);
  977. }
  978. }
  979. }
  980. //JS最后一列加上操作列
  981. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, " . ($operateButtonList ? "buttons: [" . implode(',', $operateButtonList) . "], " : "") . "formatter: Table.api.formatter.operate}";
  982. $addList = implode("\n", array_filter($addList));
  983. $editList = implode("\n", array_filter($editList));
  984. $javascriptList = implode(",\n", array_filter($javascriptList));
  985. $langList = implode(",\n", array_filter($langList));
  986. //数组等号对齐
  987. $langList = array_filter(explode(",\n", $langList . ",\n"));
  988. foreach ($langList as &$line) {
  989. if (preg_match("/^\s+'([^']+)'\s*=>\s*'([^']+)'\s*/is", $line, $matches)) {
  990. $line = " '{$matches[1]}'" . str_pad('=>', ($this->fieldMaxLen - strlen($matches[1]) + 3), ' ', STR_PAD_LEFT) . " '{$matches[2]}'";
  991. }
  992. }
  993. unset($line);
  994. $langList = implode(",\n", array_filter($langList));
  995. $fixedcolumns = count($columnList) >= 10 ? 1 : $fixedcolumns;
  996. $fixedColumnsJs = '';
  997. if (is_numeric($fixedcolumns) && $fixedcolumns) {
  998. $fixedColumnsJs = "\n" . str_repeat(" ", 16) . "fixedColumns: true,\n" . str_repeat(" ", 16) . ($fixedcolumns < 0 ? "fixedNumber" : "fixedRightNumber") . ": " . $fixedcolumns . ",";
  999. }
  1000. //表注释
  1001. $tableComment = $modelTableInfo ? $modelTableInfo['Comment'] : '';
  1002. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  1003. $modelInit = '';
  1004. if ($priKey != $order) {
  1005. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  1006. }
  1007. $data = [
  1008. 'modelConnection' => $db == 'database' ? '' : "protected \$connection = '{$db}';",
  1009. 'controllerNamespace' => $controllerNamespace,
  1010. 'modelNamespace' => $modelNamespace,
  1011. 'validateNamespace' => $validateNamespace,
  1012. 'controllerUrl' => $controllerUrl,
  1013. 'controllerName' => $controllerName,
  1014. 'controllerAssignList' => implode("\n", $controllerAssignList),
  1015. 'modelName' => $modelName,
  1016. 'modelTableName' => $modelTableName,
  1017. 'modelTableType' => $modelTableType,
  1018. 'modelTableTypeName' => $modelTableTypeName,
  1019. 'validateName' => $validateName,
  1020. 'tableComment' => $tableComment,
  1021. 'iconName' => $iconName,
  1022. 'pk' => $priKey,
  1023. 'order' => $order,
  1024. 'fixedColumnsJs' => $fixedColumnsJs,
  1025. 'table' => $table,
  1026. 'tableName' => $modelTableName,
  1027. 'addList' => $addList,
  1028. 'editList' => $editList,
  1029. 'javascriptList' => $javascriptList,
  1030. 'langList' => $langList,
  1031. 'softDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use traits\model\SoftDelete;" : '',
  1032. 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  1033. 'modelAutoWriteTimestamp' => in_array($this->createTimeField, $fieldArr) || in_array($this->updateTimeField, $fieldArr) ? "'integer'" : 'false',
  1034. 'createTime' => in_array($this->createTimeField, $fieldArr) ? "'{$this->createTimeField}'" : 'false',
  1035. 'updateTime' => in_array($this->updateTimeField, $fieldArr) ? "'{$this->updateTimeField}'" : 'false',
  1036. 'deleteTime' => in_array($this->deleteTimeField, $fieldArr) ? "'{$this->deleteTimeField}'" : 'false',
  1037. 'relationSearch' => $relations ? 'true' : 'false',
  1038. 'relationWithList' => '',
  1039. 'relationMethodList' => '',
  1040. 'controllerImport' => $controllerImport,
  1041. 'controllerIndex' => '',
  1042. 'recyclebinJs' => '',
  1043. 'headingHtml' => $headingHtml,
  1044. 'multipleHtml' => $multipleHtml,
  1045. 'importHtml' => $importHtml,
  1046. 'recyclebinHtml' => $recyclebinHtml,
  1047. 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(in_array($priKey, explode(',', $fields)) ? explode(',', $fields) : explode(',', $priKey . ',' . $fields))) . "']);" : '',
  1048. 'appendAttrList' => implode(",\n", $appendAttrList),
  1049. 'getEnumList' => implode("\n\n", $getEnumArr),
  1050. 'getAttrList' => implode("\n\n", $getAttrArr),
  1051. 'setAttrList' => implode("\n\n", $setAttrArr),
  1052. 'modelInit' => $modelInit,
  1053. ];
  1054. //如果使用关联模型
  1055. if ($relations) {
  1056. $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  1057. $relationKeyArr = ['hasone' => 'hasOne', 'belongsto' => 'belongsTo', 'hasmany' => 'hasMany'];
  1058. foreach ($relations as $index => $relation) {
  1059. //需要构造关联的方法
  1060. $relation['relationMethod'] = strtolower($relation['relationName']);
  1061. //关联的模式
  1062. $relation['relationMode'] = strtolower($relation['relationMode']);
  1063. $relation['relationMode'] = array_key_exists($relation['relationMode'], $relationKeyArr) ? $relationKeyArr[$relation['relationMode']] : '';
  1064. //关联字段
  1065. $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  1066. //构造关联模型的方法
  1067. $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod' . ($relation['relationMode'] == 'hasMany' ? '-hasmany' : ''), $relation);
  1068. if ($relation['relationMode'] == 'hasMany') {
  1069. continue;
  1070. }
  1071. //预载入的方法
  1072. $relationWithList[] = $relation['relationMethod'];
  1073. unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  1074. //如果设置了显示主表字段,则必须显式将关联表字段显示
  1075. if ($fields) {
  1076. $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
  1077. }
  1078. //显示的字段
  1079. if ($relation['relationFields']) {
  1080. $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  1081. }
  1082. }
  1083. $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  1084. $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  1085. $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  1086. if ($relationWithList) {
  1087. //需要重写index方法
  1088. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  1089. }
  1090. } elseif ($fields) {
  1091. $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  1092. //需要重写index方法
  1093. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  1094. }
  1095. // 生成控制器文件
  1096. $this->writeToFile('controller', $data, $controllerFile);
  1097. // 生成模型文件
  1098. $this->writeToFile('model', $data, $modelFile);
  1099. if ($relations) {
  1100. foreach ($relations as $i => $relation) {
  1101. $relation['modelNamespace'] = $relation['relationNamespace'];
  1102. if (!is_file($relation['relationFile'])) {
  1103. // 生成关联模型文件
  1104. $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  1105. }
  1106. }
  1107. }
  1108. // 生成验证文件
  1109. $this->writeToFile('validate', $data, $validateFile);
  1110. // 生成视图文件
  1111. $this->writeToFile('add', $data, $addFile);
  1112. $this->writeToFile('edit', $data, $editFile);
  1113. $this->writeToFile('index', $data, $indexFile);
  1114. if ($recyclebinHtml) {
  1115. $this->writeToFile('recyclebin', $data, $recyclebinFile);
  1116. $recyclebinTitle = in_array('title', $fieldArr) ? 'title' : (in_array('name', $fieldArr) ? 'name' : '');
  1117. $recyclebinTitleJs = $recyclebinTitle ? "\n {field: '{$recyclebinTitle}', title: __('" . (ucfirst($recyclebinTitle)) . "'), align: 'left'}," : '';
  1118. $data['recyclebinJs'] = $this->getReplacedStub('mixins/recyclebinjs', ['deleteTimeField' => $this->deleteTimeField, 'recyclebinTitleJs' => $recyclebinTitleJs, 'controllerUrl' => $controllerUrl]);
  1119. }
  1120. // 生成JS文件
  1121. $this->writeToFile('javascript', $data, $javascriptFile);
  1122. // 生成语言文件
  1123. $this->writeToFile('lang', $data, $langFile);
  1124. } catch (ErrorException $e) {
  1125. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  1126. }
  1127. //继续生成菜单
  1128. if ($menu) {
  1129. exec("php think menu -c {$controllerUrl}");
  1130. }
  1131. $output->info("Build Successed");
  1132. }
  1133. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  1134. {
  1135. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1136. return;
  1137. }
  1138. $fieldList = $this->getFieldListName($field);
  1139. $methodName = 'get' . ucfirst($fieldList);
  1140. foreach ($itemArr as $k => &$v) {
  1141. $v = "__('" . mb_ucfirst($v) . "')";
  1142. }
  1143. unset($v);
  1144. $itemString = $this->getArrayString($itemArr);
  1145. $getEnum[] = <<<EOD
  1146. public function {$methodName}()
  1147. {
  1148. return [{$itemString}];
  1149. }
  1150. EOD;
  1151. $controllerAssignList[] = <<<EOD
  1152. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  1153. EOD;
  1154. }
  1155. protected function getAttr(&$getAttr, $field, $inputType = '')
  1156. {
  1157. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio'])) {
  1158. return;
  1159. }
  1160. $attrField = ucfirst($this->getCamelizeName($field));
  1161. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  1162. }
  1163. protected function setAttr(&$setAttr, $field, $inputType = '')
  1164. {
  1165. if (!in_array($inputType, ['datetime', 'checkbox', 'select'])) {
  1166. return;
  1167. }
  1168. $attrField = ucfirst($this->getCamelizeName($field));
  1169. if ($inputType == 'datetime') {
  1170. $return = <<<EOD
  1171. return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  1172. EOD;
  1173. } elseif (in_array($inputType, ['checkbox', 'select'])) {
  1174. $return = <<<EOD
  1175. return is_array(\$value) ? implode(',', \$value) : \$value;
  1176. EOD;
  1177. }
  1178. $setAttr[] = <<<EOD
  1179. protected function set{$attrField}Attr(\$value)
  1180. {
  1181. $return
  1182. }
  1183. EOD;
  1184. }
  1185. protected function appendAttr(&$appendAttrList, $field)
  1186. {
  1187. $appendAttrList[] = <<<EOD
  1188. '{$field}_text'
  1189. EOD;
  1190. }
  1191. /**
  1192. * 移除相对的空目录
  1193. * @param $parseFile
  1194. * @param $parseArr
  1195. * @return bool
  1196. */
  1197. protected function removeEmptyBaseDir($parseFile, $parseArr)
  1198. {
  1199. if (count($parseArr) > 1) {
  1200. $parentDir = dirname($parseFile);
  1201. for ($i = 0; $i < count($parseArr); $i++) {
  1202. try {
  1203. $iterator = new \FilesystemIterator($parentDir);
  1204. $isDirEmpty = !$iterator->valid();
  1205. if ($isDirEmpty) {
  1206. rmdir($parentDir);
  1207. $parentDir = dirname($parentDir);
  1208. } else {
  1209. return true;
  1210. }
  1211. } catch (\UnexpectedValueException $e) {
  1212. return false;
  1213. }
  1214. }
  1215. }
  1216. return true;
  1217. }
  1218. /**
  1219. * 获取控制器URL
  1220. * @param string $moduleName
  1221. * @param array $baseNameArr
  1222. * @return string
  1223. */
  1224. protected function getControllerUrl($moduleName, $baseNameArr)
  1225. {
  1226. for ($i = 0; $i < count($baseNameArr) - 1; $i++) {
  1227. $temp = array_slice($baseNameArr, 0, $i + 1);
  1228. $temp[$i] = ucfirst($temp[$i]);
  1229. $controllerFile = APP_PATH . $moduleName . DS . 'controller' . DS . implode(DS, $temp) . '.php';
  1230. //检测父级目录同名控制器是否存在,存在则变更URL格式
  1231. if (is_file($controllerFile)) {
  1232. $baseNameArr = [implode('.', $baseNameArr)];
  1233. break;
  1234. }
  1235. }
  1236. $controllerUrl = strtolower(implode('/', $baseNameArr));
  1237. return $controllerUrl;
  1238. }
  1239. /**
  1240. * 获取控制器相关信息
  1241. * @param $module
  1242. * @param $controller
  1243. * @param $table
  1244. * @return array
  1245. */
  1246. protected function getControllerData($module, $controller, $table)
  1247. {
  1248. return $this->getParseNameData($module, $controller, $table, 'controller');
  1249. }
  1250. /**
  1251. * 获取模型相关信息
  1252. * @param $module
  1253. * @param $model
  1254. * @param $table
  1255. * @return array
  1256. */
  1257. protected function getModelData($module, $model, $table)
  1258. {
  1259. return $this->getParseNameData($module, $model, $table, 'model');
  1260. }
  1261. /**
  1262. * 获取验证器相关信息
  1263. * @param $module
  1264. * @param $validate
  1265. * @param $table
  1266. * @return array
  1267. */
  1268. protected function getValidateData($module, $validate, $table)
  1269. {
  1270. return $this->getParseNameData($module, $validate, $table, 'validate');
  1271. }
  1272. /**
  1273. * 获取已解析相关信息
  1274. * @param string $module 模块名称
  1275. * @param string $name 自定义名称
  1276. * @param string $table 数据表名
  1277. * @param string $type 解析类型,本例中为controller、model、validate
  1278. * @return array
  1279. */
  1280. protected function getParseNameData($module, $name, $table, $type)
  1281. {
  1282. $arr = [];
  1283. if (!$name) {
  1284. $parseName = Loader::parseName($table, 1);
  1285. $name = str_replace('_', '/', $table);
  1286. }
  1287. $name = str_replace(['.', '/', '\\'], '/', $name);
  1288. $arr = explode('/', $name);
  1289. $parseName = ucfirst(array_pop($arr));
  1290. $parseArr = $arr;
  1291. array_push($parseArr, $parseName);
  1292. //类名不能为内部关键字
  1293. if (in_array(strtolower($parseName), $this->internalKeywords)) {
  1294. throw new Exception('Unable to use internal variable:' . $parseName);
  1295. }
  1296. $appNamespace = Config::get('app_namespace');
  1297. $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
  1298. $moduleDir = APP_PATH . $module . DS;
  1299. $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  1300. return [$parseNamespace, $parseName, $parseFile, $parseArr];
  1301. }
  1302. /**
  1303. * 写入到文件
  1304. * @param string $name
  1305. * @param array $data
  1306. * @param string $pathname
  1307. * @return mixed
  1308. */
  1309. protected function writeToFile($name, $data, $pathname)
  1310. {
  1311. foreach ($data as $index => &$datum) {
  1312. $datum = is_array($datum) ? '' : $datum;
  1313. }
  1314. unset($datum);
  1315. $content = $this->getReplacedStub($name, $data);
  1316. if (!is_dir(dirname($pathname))) {
  1317. mkdir(dirname($pathname), 0755, true);
  1318. }
  1319. return file_put_contents($pathname, $content);
  1320. }
  1321. /**
  1322. * 获取替换后的数据
  1323. * @param string $name
  1324. * @param array $data
  1325. * @return string
  1326. */
  1327. protected function getReplacedStub($name, $data)
  1328. {
  1329. foreach ($data as $index => &$datum) {
  1330. $datum = is_array($datum) ? '' : $datum;
  1331. }
  1332. unset($datum);
  1333. $search = $replace = [];
  1334. foreach ($data as $k => $v) {
  1335. $search[] = "{%{$k}%}";
  1336. $replace[] = $v;
  1337. }
  1338. $stubname = $this->getStub($name);
  1339. if (isset($this->stubList[$stubname])) {
  1340. $stub = $this->stubList[$stubname];
  1341. } else {
  1342. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  1343. }
  1344. $content = str_replace($search, $replace, $stub);
  1345. return $content;
  1346. }
  1347. /**
  1348. * 获取基础模板
  1349. * @param string $name
  1350. * @return string
  1351. */
  1352. protected function getStub($name)
  1353. {
  1354. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  1355. }
  1356. protected function getLangItem($field, $content)
  1357. {
  1358. if ($content || !Lang::has($field)) {
  1359. $this->fieldMaxLen = strlen($field) > $this->fieldMaxLen ? strlen($field) : $this->fieldMaxLen;
  1360. $content = str_replace(',', ',', $content);
  1361. if (stripos($content, ':') !== false && stripos($content, '=') !== false) {
  1362. list($fieldLang, $item) = explode(':', $content);
  1363. $itemArr = [$field => $fieldLang];
  1364. foreach (explode(',', $item) as $k => $v) {
  1365. $valArr = explode('=', $v);
  1366. if (count($valArr) == 2) {
  1367. list($key, $value) = $valArr;
  1368. $itemArr[$field . ' ' . $key] = $value;
  1369. if ($this->headingFilterField == $field) {
  1370. $itemArr['Set ' . $field . ' to ' . $key] = '设为' . $value;
  1371. }
  1372. $this->fieldMaxLen = strlen($field . ' ' . $key) > $this->fieldMaxLen ? strlen($field . ' ' . $key) : $this->fieldMaxLen;
  1373. }
  1374. }
  1375. } else {
  1376. $itemArr = [$field => $content];
  1377. }
  1378. $resultArr = [];
  1379. foreach ($itemArr as $k => $v) {
  1380. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  1381. }
  1382. return implode(",\n", $resultArr);
  1383. } else {
  1384. return '';
  1385. }
  1386. }
  1387. /**
  1388. * 读取数据和语言数组列表
  1389. * @param array $arr
  1390. * @param boolean $withTpl
  1391. * @return array
  1392. */
  1393. protected function getLangArray($arr, $withTpl = true)
  1394. {
  1395. $langArr = [];
  1396. foreach ($arr as $k => $v) {
  1397. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  1398. }
  1399. return $langArr;
  1400. }
  1401. /**
  1402. * 将数据转换成带字符串
  1403. * @param array $arr
  1404. * @return string
  1405. */
  1406. protected function getArrayString($arr)
  1407. {
  1408. if (!is_array($arr)) {
  1409. return $arr;
  1410. }
  1411. $stringArr = [];
  1412. foreach ($arr as $k => $v) {
  1413. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  1414. if (!$is_var) {
  1415. $v = str_replace("'", "\'", $v);
  1416. $k = str_replace("'", "\'", $k);
  1417. }
  1418. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  1419. }
  1420. return implode(", ", $stringArr);
  1421. }
  1422. protected function getItemArray($item, $field, $comment)
  1423. {
  1424. $itemArr = [];
  1425. $comment = str_replace(',', ',', $comment);
  1426. if (stripos($comment, ':') !== false && stripos($comment, '=') !== false) {
  1427. list($fieldLang, $item) = explode(':', $comment);
  1428. $itemArr = [];
  1429. foreach (explode(',', $item) as $k => $v) {
  1430. $valArr = explode('=', $v);
  1431. if (count($valArr) == 2) {
  1432. list($key, $value) = $valArr;
  1433. $itemArr[$key] = $field . ' ' . $key;
  1434. }
  1435. }
  1436. } else {
  1437. foreach ($item as $k => $v) {
  1438. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  1439. }
  1440. }
  1441. return $itemArr;
  1442. }
  1443. protected function getFieldType(&$v)
  1444. {
  1445. $inputType = 'text';
  1446. switch ($v['DATA_TYPE']) {
  1447. case 'bigint':
  1448. case 'int':
  1449. case 'mediumint':
  1450. case 'smallint':
  1451. case 'tinyint':
  1452. $inputType = 'number';
  1453. break;
  1454. case 'enum':
  1455. case 'set':
  1456. $inputType = 'select';
  1457. break;
  1458. case 'decimal':
  1459. case 'double':
  1460. case 'float':
  1461. $inputType = 'number';
  1462. break;
  1463. case 'longtext':
  1464. case 'text':
  1465. case 'mediumtext':
  1466. case 'smalltext':
  1467. case 'tinytext':
  1468. $inputType = 'textarea';
  1469. break;
  1470. case 'year':
  1471. case 'date':
  1472. case 'time':
  1473. case 'datetime':
  1474. case 'timestamp':
  1475. $inputType = 'datetime';
  1476. break;
  1477. default:
  1478. break;
  1479. }
  1480. $fieldsName = $v['COLUMN_NAME'];
  1481. // 指定后缀说明也是个时间字段
  1482. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  1483. $inputType = 'datetime';
  1484. }
  1485. // 指定后缀结尾且类型为enum,说明是个单选框
  1486. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  1487. $inputType = "radio";
  1488. }
  1489. // 指定后缀结尾且类型为set,说明是个复选框
  1490. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  1491. $inputType = "checkbox";
  1492. }
  1493. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1494. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1495. $inputType = "switch";
  1496. }
  1497. // 指定后缀结尾城市选择框
  1498. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1499. $inputType = "citypicker";
  1500. }
  1501. // 指定后缀结尾城市选择框
  1502. if ($this->isMatchSuffix($fieldsName, $this->rangeSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1503. $inputType = "datetimerange";
  1504. }
  1505. // 指定后缀结尾JSON配置
  1506. if ($this->isMatchSuffix($fieldsName, $this->jsonSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1507. $inputType = "fieldlist";
  1508. }
  1509. // 指定后缀结尾标签配置
  1510. if ($this->isMatchSuffix($fieldsName, $this->tagSuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'text')) {
  1511. $inputType = "tagsinput";
  1512. }
  1513. return $inputType;
  1514. }
  1515. /**
  1516. * 判断是否符合指定后缀
  1517. * @param string $field 字段名称
  1518. * @param mixed $suffixArr 后缀
  1519. * @return boolean
  1520. */
  1521. protected function isMatchSuffix($field, $suffixArr)
  1522. {
  1523. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1524. foreach ($suffixArr as $k => $v) {
  1525. if (preg_match("/{$v}$/i", $field)) {
  1526. return true;
  1527. }
  1528. }
  1529. return false;
  1530. }
  1531. /**
  1532. * 获取表单分组数据
  1533. * @param string $field
  1534. * @param string $content
  1535. * @return string
  1536. */
  1537. protected function getFormGroup($field, $content)
  1538. {
  1539. $langField = mb_ucfirst($field);
  1540. return <<<EOD
  1541. <div class="form-group">
  1542. <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1543. <div class="col-xs-12 col-sm-8">
  1544. {$content}
  1545. </div>
  1546. </div>
  1547. EOD;
  1548. }
  1549. /**
  1550. * 获取图片模板数据
  1551. * @param string $field
  1552. * @param string $content
  1553. * @return string
  1554. */
  1555. protected function getImageUpload($field, $content)
  1556. {
  1557. $uploadfilter = $selectfilter = '';
  1558. if ($this->isMatchSuffix($field, $this->imageField)) {
  1559. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp,image/webp"';
  1560. $selectfilter = ' data-mimetype="image/*"';
  1561. }
  1562. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1563. $preview = ' data-preview-id="p-' . $field . '"';
  1564. $previewcontainer = $preview ? '<ul class="row list-inline faupload-preview" id="p-' . $field . '"></ul>' : '';
  1565. return <<<EOD
  1566. <div class="input-group">
  1567. {$content}
  1568. <div class="input-group-addon no-border no-padding">
  1569. <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>
  1570. <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>
  1571. </div>
  1572. <span class="msg-box n-right" for="c-{$field}"></span>
  1573. </div>
  1574. {$previewcontainer}
  1575. EOD;
  1576. }
  1577. /**
  1578. * 获取JS列数据
  1579. * @param string $field
  1580. * @param string $datatype
  1581. * @param string $extend
  1582. * @param array $itemArr
  1583. * @param array $fieldConfig
  1584. * @return string
  1585. */
  1586. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [], $fieldConfig = [])
  1587. {
  1588. $lang = mb_ucfirst($field);
  1589. $formatter = '';
  1590. foreach ($this->fieldFormatterSuffix as $k => $v) {
  1591. if (preg_match("/{$k}$/i", $field)) {
  1592. if (is_array($v)) {
  1593. if (in_array($datatype, $v['type'])) {
  1594. $formatter = $v['name'];
  1595. break;
  1596. }
  1597. } else {
  1598. $formatter = $v;
  1599. break;
  1600. }
  1601. }
  1602. }
  1603. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  1604. if ($datatype == 'set') {
  1605. $formatter = 'label';
  1606. }
  1607. foreach ($itemArr as $k => &$v) {
  1608. if (substr($v, 0, 3) !== '__(') {
  1609. $v = "__('" . mb_ucfirst($v) . "')";
  1610. }
  1611. }
  1612. unset($v);
  1613. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
  1614. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1615. if ($itemArr) {
  1616. $html .= ", searchList: " . $searchList;
  1617. }
  1618. // 文件、图片、权重等字段默认不加入搜索栏,字符串类型默认LIKE
  1619. $noSearchFiles = ['file$', 'files$', 'image$', 'images$', '^weigh$'];
  1620. if (preg_match("/" . implode('|', $noSearchFiles) . "/i", $field)) {
  1621. $html .= ", operate: false";
  1622. } elseif (in_array($datatype, ['varchar'])) {
  1623. $html .= ", operate: 'LIKE'";
  1624. }
  1625. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1626. $html .= ", operate:'RANGE', addclass:'datetimerange', autocomplete:false";
  1627. } elseif (in_array($datatype, ['float', 'double', 'decimal'])) {
  1628. $html .= ", operate:'BETWEEN'";
  1629. }
  1630. if (in_array($datatype, ['set'])) {
  1631. $html .= ", operate:'FIND_IN_SET'";
  1632. }
  1633. if (isset($fieldConfig['CHARACTER_MAXIMUM_LENGTH']) && $fieldConfig['CHARACTER_MAXIMUM_LENGTH'] >= 255 && in_array($datatype, ['varchar']) && !$formatter) {
  1634. $formatter = 'content';
  1635. $html .= ", table: table, class: 'autocontent'";
  1636. }
  1637. if (in_array($formatter, ['image', 'images'])) {
  1638. $html .= ", events: Table.api.events.image";
  1639. }
  1640. if (in_array($formatter, ['toggle'])) {
  1641. $html .= ", table: table";
  1642. }
  1643. if ($itemArr && !$formatter) {
  1644. $formatter = 'normal';
  1645. }
  1646. if ($formatter) {
  1647. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1648. } else {
  1649. $html .= "}";
  1650. }
  1651. return $html;
  1652. }
  1653. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1654. {
  1655. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1656. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1657. }
  1658. protected function getFieldListName($field)
  1659. {
  1660. return $this->getCamelizeName($field) . 'List';
  1661. }
  1662. }