Crud.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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. $stateNoClass = 'fa-flip-horizontal text-gray';
  546. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldYes' => $yes, 'fieldNo' => $no, 'attrStr' => Form::attributes($attrArr), 'fieldValue' => $defaultValue, 'fieldSwitchClass' => $defaultValue == $no ? $stateNoClass : '']);
  547. $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}"]);
  548. } else if ($inputType == 'citypicker') {
  549. $attrArr['class'] = implode(' ', $cssClassArr);
  550. $attrArr['data-toggle'] = "city-picker";
  551. $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
  552. $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
  553. } else {
  554. $search = $replace = '';
  555. //特殊字段为关联搜索
  556. if ($this->isMatchSuffix($field, $this->selectpageSuffix)) {
  557. $inputType = 'text';
  558. $defaultValue = '';
  559. $attrArr['data-rule'] = 'required';
  560. $cssClassArr[] = 'selectpage';
  561. $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
  562. $attrArr['data-source'] = $selectpageController . "/index";
  563. //如果是类型表需要特殊处理下
  564. if ($selectpageController == 'category') {
  565. $attrArr['data-source'] = 'category/selectpage';
  566. $attrArr['data-params'] = '##replacetext##';
  567. $search = '"##replacetext##"';
  568. $replace = '\'{"custom[type]":"' . $table . '"}\'';
  569. } elseif ($selectpageController == 'admin') {
  570. $attrArr['data-source'] = 'auth/admin/selectpage';
  571. } elseif ($selectpageController == 'user') {
  572. $attrArr['data-source'] = 'user/user/index';
  573. }
  574. if ($this->isMatchSuffix($field, $this->selectpagesSuffix)) {
  575. $attrArr['data-multiple'] = 'true';
  576. }
  577. foreach ($this->fieldSelectpageMap as $m => $n) {
  578. if (in_array($field, $n)) {
  579. $attrArr['data-field'] = $m;
  580. break;
  581. }
  582. }
  583. }
  584. //因为有自动完成可输入其它内容
  585. $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  586. $attrArr['class'] = implode(' ', $cssClassArr);
  587. $isUpload = false;
  588. if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField))) {
  589. $isUpload = true;
  590. }
  591. //如果是步长则加上步长
  592. if ($step) {
  593. $attrArr['step'] = $step;
  594. }
  595. //如果是图片加上个size
  596. if ($isUpload) {
  597. $attrArr['size'] = 50;
  598. }
  599. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  600. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  601. if ($search && $replace) {
  602. $formAddElement = str_replace($search, $replace, $formAddElement);
  603. $formEditElement = str_replace($search, $replace, $formEditElement);
  604. }
  605. //如果是图片或文件
  606. if ($isUpload) {
  607. $formAddElement = $this->getImageUpload($field, $formAddElement);
  608. $formEditElement = $this->getImageUpload($field, $formEditElement);
  609. }
  610. }
  611. //构造添加和编辑HTML信息
  612. $addList[] = $this->getFormGroup($field, $formAddElement);
  613. $editList[] = $this->getFormGroup($field, $formEditElement);
  614. }
  615. //过滤text类型字段
  616. if ($v['DATA_TYPE'] != 'text') {
  617. //主键
  618. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined) {
  619. $priDefined = TRUE;
  620. $javascriptList[] = "{checkbox: true}";
  621. }
  622. if (!$fields || in_array($field, explode(',', $fields))) {
  623. //构造JS列信息
  624. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  625. }
  626. //排序方式,如果有指定排序字段,否则按主键排序
  627. $order = $field == $this->sortField ? $this->sortField : $order;
  628. }
  629. }
  630. //循环关联表,追加语言包和JS列
  631. foreach ($relations as $index => $relation) {
  632. foreach ($relation['relationColumnList'] as $k => $v) {
  633. // 不显示的字段直接过滤掉
  634. if ($relation['relationFields'] && !in_array($v['COLUMN_NAME'], $relation['relationFields'])) {
  635. continue;
  636. }
  637. $relationField = strtolower($relation['relationName']) . "." . $v['COLUMN_NAME'];
  638. // 语言列表
  639. if ($v['COLUMN_COMMENT'] != '') {
  640. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  641. }
  642. //过滤text类型字段
  643. if ($v['DATA_TYPE'] != 'text') {
  644. //构造JS列信息
  645. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  646. }
  647. }
  648. }
  649. //JS最后一列加上操作列
  650. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  651. $addList = implode("\n", array_filter($addList));
  652. $editList = implode("\n", array_filter($editList));
  653. $javascriptList = implode(",\n", array_filter($javascriptList));
  654. $langList = implode(",\n", array_filter($langList));
  655. //表注释
  656. $tableComment = $modelTableInfo['Comment'];
  657. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  658. $modelInit = '';
  659. if ($priKey != $order) {
  660. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  661. }
  662. $data = [
  663. 'controllerNamespace' => $controllerNamespace,
  664. 'modelNamespace' => $modelNamespace,
  665. 'validateNamespace' => $validateNamespace,
  666. 'controllerUrl' => $controllerUrl,
  667. 'controllerName' => $controllerName,
  668. 'controllerAssignList' => implode("\n", $controllerAssignList),
  669. 'modelName' => $modelName,
  670. 'modelTableName' => $modelTableName,
  671. 'modelTableType' => $modelTableType,
  672. 'modelTableTypeName' => $modelTableTypeName,
  673. 'validateName' => $validateName,
  674. 'tableComment' => $tableComment,
  675. 'iconName' => $iconName,
  676. 'pk' => $priKey,
  677. 'order' => $order,
  678. 'table' => $table,
  679. 'tableName' => $modelTableName,
  680. 'addList' => $addList,
  681. 'editList' => $editList,
  682. 'javascriptList' => $javascriptList,
  683. 'langList' => $langList,
  684. 'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
  685. 'createTime' => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
  686. 'updateTime' => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
  687. 'relationSearch' => $relations ? 'true' : 'false',
  688. 'relationWithList' => '',
  689. 'relationMethodList' => '',
  690. 'controllerIndex' => '',
  691. 'visibleFieldList' => $fields ? "\$row->visible(['" . implode("','", array_filter(explode(',', $fields))) . "']);" : '',
  692. 'appendAttrList' => implode(",\n", $appendAttrList),
  693. 'getEnumList' => implode("\n\n", $getEnumArr),
  694. 'getAttrList' => implode("\n\n", $getAttrArr),
  695. 'setAttrList' => implode("\n\n", $setAttrArr),
  696. 'modelInit' => $modelInit,
  697. ];
  698. //如果使用关联模型
  699. if ($relations) {
  700. $relationWithList = $relationMethodList = $relationVisibleFieldList = [];
  701. foreach ($relations as $index => $relation) {
  702. //需要构造关联的方法
  703. $relation['relationMethod'] = strtolower($relation['relationName']);
  704. //关联的模式
  705. $relation['relationMode'] = $relation['relationMode'] == 'hasone' ? 'hasOne' : 'belongsTo';
  706. //关联字段
  707. $relation['relationForeignKey'] = $relation['relationForeignKey'];
  708. $relation['relationPrimaryKey'] = $relation['relationPrimaryKey'] ? $relation['relationPrimaryKey'] : $priKey;
  709. //预载入的方法
  710. $relationWithList[] = $relation['relationMethod'];
  711. unset($relation['relationColumnList'], $relation['relationFieldList'], $relation['relationTableInfo']);
  712. //构造关联模型的方法
  713. $relationMethodList[] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $relation);
  714. //如果设置了显示主表字段,则必须显式将关联表字段显示
  715. if ($fields) {
  716. $relationVisibleFieldList[] = "\$row->visible(['{$relation['relationMethod']}']);";
  717. }
  718. //显示的字段
  719. if ($relation['relationFields']) {
  720. $relationVisibleFieldList[] = "\$row->getRelation('" . $relation['relationMethod'] . "')->visible(['" . implode("','", $relation['relationFields']) . "']);";
  721. }
  722. }
  723. $data['relationWithList'] = "->with(['" . implode("','", $relationWithList) . "'])";
  724. $data['relationMethodList'] = implode("\n\n", $relationMethodList);
  725. $data['relationVisibleFieldList'] = implode("\n\t\t\t\t", $relationVisibleFieldList);
  726. //需要重写index方法
  727. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  728. } else if ($fields) {
  729. $data = array_merge($data, ['relationWithList' => '', 'relationMethodList' => '', 'relationVisibleFieldList' => '']);
  730. //需要重写index方法
  731. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  732. }
  733. // 生成控制器文件
  734. $result = $this->writeToFile('controller', $data, $controllerFile);
  735. // 生成模型文件
  736. $result = $this->writeToFile('model', $data, $modelFile);
  737. if ($relations) {
  738. foreach ($relations as $i => $relation) {
  739. $relation['modelNamespace'] = $data['modelNamespace'];
  740. if (!is_file($relation['relationFile'])) {
  741. // 生成关联模型文件
  742. $result = $this->writeToFile('relationmodel', $relation, $relation['relationFile']);
  743. }
  744. }
  745. }
  746. // 生成验证文件
  747. $result = $this->writeToFile('validate', $data, $validateFile);
  748. // 生成视图文件
  749. $result = $this->writeToFile('add', $data, $addFile);
  750. $result = $this->writeToFile('edit', $data, $editFile);
  751. $result = $this->writeToFile('index', $data, $indexFile);
  752. // 生成JS文件
  753. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  754. // 生成语言文件
  755. if ($langList) {
  756. $result = $this->writeToFile('lang', $data, $langFile);
  757. }
  758. } catch (\think\exception\ErrorException $e) {
  759. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  760. }
  761. //继续生成菜单
  762. if ($menu) {
  763. exec("php think menu -c {$controllerUrl}");
  764. }
  765. $output->info("Build Successed");
  766. }
  767. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  768. {
  769. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  770. return;
  771. $fieldList = $this->getFieldListName($field);
  772. $methodName = 'get' . ucfirst($fieldList);
  773. foreach ($itemArr as $k => &$v) {
  774. $v = "__('" . mb_ucfirst($v) . "')";
  775. }
  776. unset($v);
  777. $itemString = $this->getArrayString($itemArr);
  778. $getEnum[] = <<<EOD
  779. public function {$methodName}()
  780. {
  781. return [{$itemString}];
  782. }
  783. EOD;
  784. $controllerAssignList[] = <<<EOD
  785. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  786. EOD;
  787. }
  788. protected function getAttr(&$getAttr, $field, $inputType = '')
  789. {
  790. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  791. return;
  792. $attrField = ucfirst($this->getCamelizeName($field));
  793. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  794. }
  795. protected function setAttr(&$setAttr, $field, $inputType = '')
  796. {
  797. if (!in_array($inputType, ['datetime', 'checkbox', 'select']))
  798. return;
  799. $attrField = ucfirst($this->getCamelizeName($field));
  800. if ($inputType == 'datetime') {
  801. $return = <<<EOD
  802. return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
  803. EOD;
  804. } else if (in_array($inputType, ['checkbox', 'select'])) {
  805. $return = <<<EOD
  806. return is_array(\$value) ? implode(',', \$value) : \$value;
  807. EOD;
  808. }
  809. $setAttr[] = <<<EOD
  810. protected function set{$attrField}Attr(\$value)
  811. {
  812. $return
  813. }
  814. EOD;
  815. }
  816. protected function appendAttr(&$appendAttrList, $field)
  817. {
  818. $appendAttrList[] = <<<EOD
  819. '{$field}_text'
  820. EOD;
  821. }
  822. /**
  823. * 移除相对的空目录
  824. * @param $parseFile
  825. * @param $parseArr
  826. * @return bool
  827. */
  828. protected function removeEmptyBaseDir($parseFile, $parseArr)
  829. {
  830. if (count($parseArr) > 1) {
  831. $parentDir = dirname($parseFile);
  832. for ($i = 0; $i < count($parseArr); $i++) {
  833. $iterator = new \FilesystemIterator($parentDir);
  834. $isDirEmpty = !$iterator->valid();
  835. if ($isDirEmpty) {
  836. rmdir($parentDir);
  837. $parentDir = dirname($parentDir);
  838. } else {
  839. return true;
  840. }
  841. }
  842. }
  843. return true;
  844. }
  845. /**
  846. * 获取控制器相关信息
  847. * @param $module
  848. * @param $controller
  849. * @param $table
  850. * @return array
  851. */
  852. protected function getControllerData($module, $controller, $table)
  853. {
  854. return $this->getParseNameData($module, $controller, $table, 'controller');
  855. }
  856. /**
  857. * 获取模型相关信息
  858. * @param $module
  859. * @param $model
  860. * @param $table
  861. * @return array
  862. */
  863. protected function getModelData($module, $model, $table)
  864. {
  865. return $this->getParseNameData($module, $model, $table, 'model');
  866. }
  867. /**
  868. * 获取验证器相关信息
  869. * @param $module
  870. * @param $validate
  871. * @param $table
  872. * @return array
  873. */
  874. protected function getValidateData($module, $validate, $table)
  875. {
  876. return $this->getParseNameData($module, $validate, $table, 'validate');
  877. }
  878. /**
  879. * 获取已解析相关信息
  880. * @param $module
  881. * @param $name
  882. * @param $table
  883. * @param $type
  884. * @return array
  885. */
  886. protected function getParseNameData($module, $name, $table, $type)
  887. {
  888. $arr = [];
  889. if (!$name) {
  890. $arr = explode('_', strtolower($table));
  891. } else {
  892. $name = str_replace(['.', '/', '\\'], '/', $name);
  893. $arr = explode('/', $name);
  894. }
  895. $parseName = ucfirst(array_pop($arr));
  896. $appNamespace = Config::get('app_namespace');
  897. $parseNamespace = "{$appNamespace}\\{$module}\\{$type}" . ($arr ? "\\" . implode("\\", $arr) : "");
  898. $moduleDir = APP_PATH . $module . DS;
  899. $parseFile = $moduleDir . $type . DS . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  900. $parseArr = $arr;
  901. $parseArr[] = $parseName;
  902. return [$parseNamespace, $parseName, $parseFile, $parseArr];
  903. }
  904. /**
  905. * 写入到文件
  906. * @param string $name
  907. * @param array $data
  908. * @param string $pathname
  909. * @return mixed
  910. */
  911. protected function writeToFile($name, $data, $pathname)
  912. {
  913. foreach ($data as $index => &$datum) {
  914. $datum = is_array($datum) ? '' : $datum;
  915. }
  916. unset($datum);
  917. $content = $this->getReplacedStub($name, $data);
  918. if (!is_dir(dirname($pathname))) {
  919. mkdir(dirname($pathname), 0755, true);
  920. }
  921. return file_put_contents($pathname, $content);
  922. }
  923. /**
  924. * 获取替换后的数据
  925. * @param string $name
  926. * @param array $data
  927. * @return string
  928. */
  929. protected function getReplacedStub($name, $data)
  930. {
  931. foreach ($data as $index => &$datum) {
  932. $datum = is_array($datum) ? '' : $datum;
  933. }
  934. unset($datum);
  935. $search = $replace = [];
  936. foreach ($data as $k => $v) {
  937. $search[] = "{%{$k}%}";
  938. $replace[] = $v;
  939. }
  940. $stubname = $this->getStub($name);
  941. if (isset($this->stubList[$stubname])) {
  942. $stub = $this->stubList[$stubname];
  943. } else {
  944. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  945. }
  946. $content = str_replace($search, $replace, $stub);
  947. return $content;
  948. }
  949. /**
  950. * 获取基础模板
  951. * @param string $name
  952. * @return string
  953. */
  954. protected function getStub($name)
  955. {
  956. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  957. }
  958. protected function getLangItem($field, $content)
  959. {
  960. if ($content || !Lang::has($field)) {
  961. $itemArr = [];
  962. $content = str_replace(',', ',', $content);
  963. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false) {
  964. list($fieldLang, $item) = explode(':', $content);
  965. $itemArr = [$field => $fieldLang];
  966. foreach (explode(',', $item) as $k => $v) {
  967. $valArr = explode('=', $v);
  968. if (count($valArr) == 2) {
  969. list($key, $value) = $valArr;
  970. $itemArr[$field . ' ' . $key] = $value;
  971. }
  972. }
  973. } else {
  974. $itemArr = [$field => $content];
  975. }
  976. $resultArr = [];
  977. foreach ($itemArr as $k => $v) {
  978. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  979. }
  980. return implode(",\n", $resultArr);
  981. } else {
  982. return '';
  983. }
  984. }
  985. /**
  986. * 读取数据和语言数组列表
  987. * @param array $arr
  988. * @param boolean $withTpl
  989. * @return array
  990. */
  991. protected function getLangArray($arr, $withTpl = TRUE)
  992. {
  993. $langArr = [];
  994. foreach ($arr as $k => $v) {
  995. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  996. }
  997. return $langArr;
  998. }
  999. /**
  1000. * 将数据转换成带字符串
  1001. * @param array $arr
  1002. * @return string
  1003. */
  1004. protected function getArrayString($arr)
  1005. {
  1006. if (!is_array($arr))
  1007. return $arr;
  1008. $stringArr = [];
  1009. foreach ($arr as $k => $v) {
  1010. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  1011. if (!$is_var) {
  1012. $v = str_replace("'", "\'", $v);
  1013. $k = str_replace("'", "\'", $k);
  1014. }
  1015. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  1016. }
  1017. return implode(",", $stringArr);
  1018. }
  1019. protected function getItemArray($item, $field, $comment)
  1020. {
  1021. $itemArr = [];
  1022. $comment = str_replace(',', ',', $comment);
  1023. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false) {
  1024. list($fieldLang, $item) = explode(':', $comment);
  1025. $itemArr = [];
  1026. foreach (explode(',', $item) as $k => $v) {
  1027. $valArr = explode('=', $v);
  1028. if (count($valArr) == 2) {
  1029. list($key, $value) = $valArr;
  1030. $itemArr[$key] = $field . ' ' . $key;
  1031. }
  1032. }
  1033. } else {
  1034. foreach ($item as $k => $v) {
  1035. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  1036. }
  1037. }
  1038. return $itemArr;
  1039. }
  1040. protected function getFieldType(& $v)
  1041. {
  1042. $inputType = 'text';
  1043. switch ($v['DATA_TYPE']) {
  1044. case 'bigint':
  1045. case 'int':
  1046. case 'mediumint':
  1047. case 'smallint':
  1048. case 'tinyint':
  1049. $inputType = 'number';
  1050. break;
  1051. case 'enum':
  1052. case 'set':
  1053. $inputType = 'select';
  1054. break;
  1055. case 'decimal':
  1056. case 'double':
  1057. case 'float':
  1058. $inputType = 'number';
  1059. break;
  1060. case 'longtext':
  1061. case 'text':
  1062. case 'mediumtext':
  1063. case 'smalltext':
  1064. case 'tinytext':
  1065. $inputType = 'textarea';
  1066. break;
  1067. case 'year';
  1068. case 'date';
  1069. case 'time';
  1070. case 'datetime';
  1071. case 'timestamp';
  1072. $inputType = 'datetime';
  1073. break;
  1074. default:
  1075. break;
  1076. }
  1077. $fieldsName = $v['COLUMN_NAME'];
  1078. // 指定后缀说明也是个时间字段
  1079. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  1080. $inputType = 'datetime';
  1081. }
  1082. // 指定后缀结尾且类型为enum,说明是个单选框
  1083. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  1084. $inputType = "radio";
  1085. }
  1086. // 指定后缀结尾且类型为set,说明是个复选框
  1087. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set') {
  1088. $inputType = "checkbox";
  1089. }
  1090. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1091. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  1092. $inputType = "switch";
  1093. }
  1094. // 指定后缀结尾城市选择框
  1095. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char')) {
  1096. $inputType = "citypicker";
  1097. }
  1098. return $inputType;
  1099. }
  1100. /**
  1101. * 判断是否符合指定后缀
  1102. * @param string $field 字段名称
  1103. * @param mixed $suffixArr 后缀
  1104. * @return boolean
  1105. */
  1106. protected function isMatchSuffix($field, $suffixArr)
  1107. {
  1108. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1109. foreach ($suffixArr as $k => $v) {
  1110. if (preg_match("/{$v}$/i", $field)) {
  1111. return true;
  1112. }
  1113. }
  1114. return false;
  1115. }
  1116. /**
  1117. * 获取表单分组数据
  1118. * @param string $field
  1119. * @param string $content
  1120. * @return string
  1121. */
  1122. protected function getFormGroup($field, $content)
  1123. {
  1124. $langField = mb_ucfirst($field);
  1125. return <<<EOD
  1126. <div class="form-group">
  1127. <label class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1128. <div class="col-xs-12 col-sm-8">
  1129. {$content}
  1130. </div>
  1131. </div>
  1132. EOD;
  1133. }
  1134. /**
  1135. * 获取图片模板数据
  1136. * @param string $field
  1137. * @param string $content
  1138. * @return string
  1139. */
  1140. protected function getImageUpload($field, $content)
  1141. {
  1142. $uploadfilter = $selectfilter = '';
  1143. if ($this->isMatchSuffix($field, $this->imageField)) {
  1144. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1145. $selectfilter = ' data-mimetype="image/*"';
  1146. }
  1147. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1148. $preview = $uploadfilter ? ' data-preview-id="p-' . $field . '"' : '';
  1149. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  1150. return <<<EOD
  1151. <div class="input-group">
  1152. {$content}
  1153. <div class="input-group-addon no-border no-padding">
  1154. <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>
  1155. <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>
  1156. </div>
  1157. <span class="msg-box n-right" for="c-{$field}"></span>
  1158. </div>
  1159. {$previewcontainer}
  1160. EOD;
  1161. }
  1162. /**
  1163. * 获取JS列数据
  1164. * @param string $field
  1165. * @param string $datatype
  1166. * @param string $extend
  1167. * @param array $itemArr
  1168. * @return string
  1169. */
  1170. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1171. {
  1172. $lang = mb_ucfirst($field);
  1173. $formatter = '';
  1174. foreach ($this->fieldFormatterSuffix as $k => $v) {
  1175. if (preg_match("/{$k}$/i", $field)) {
  1176. if (is_array($v)) {
  1177. if (in_array($datatype, $v['type'])) {
  1178. $formatter = $v['name'];
  1179. break;
  1180. }
  1181. } else {
  1182. $formatter = $v;
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
  1188. if ($datatype == 'set') {
  1189. $formatter = 'label';
  1190. }
  1191. foreach ($itemArr as $k => &$v) {
  1192. if (substr($v, 0, 3) !== '__(')
  1193. $v = "__('" . mb_ucfirst($v) . "')";
  1194. }
  1195. unset($v);
  1196. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
  1197. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1198. if ($itemArr) {
  1199. $html .= ", searchList: " . $searchList;
  1200. }
  1201. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime') {
  1202. $html .= ", operate:'RANGE', addclass:'datetimerange'";
  1203. } else if (in_array($datatype, ['float', 'double', 'decimal'])) {
  1204. $html .= ", operate:'BETWEEN'";
  1205. }
  1206. if (in_array($datatype, ['set'])) {
  1207. $html .= ", operate:'FIND_IN_SET'";
  1208. }
  1209. if ($itemArr && !$formatter) {
  1210. $formatter = 'normal';
  1211. }
  1212. if ($formatter)
  1213. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1214. else
  1215. $html .= "}";
  1216. return $html;
  1217. }
  1218. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1219. {
  1220. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1221. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1222. }
  1223. protected function getFieldListName($field)
  1224. {
  1225. return $this->getCamelizeName($field) . 'List';
  1226. }
  1227. }