Crud.php 67 KB

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