Crud.php 67 KB

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