Crud.php 80 KB

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