Crud.php 67 KB

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