Crud.php 79 KB

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