Crud.php 59 KB

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