Crud.php 72 KB

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