Crud.php 66 KB

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