Crud.php 78 KB

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