Crud.php 58 KB

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