Crud.php 64 KB

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