Crud.php 64 KB

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