Crud.php 67 KB

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