Crud.php 62 KB

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