Crud.php 62 KB

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