Нема описа
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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