Crud.php 79 KB

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