Crud.php 60 KB

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