MakeAdmin.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace qiniu\command;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\input\Option;
  15. use think\console\Output;
  16. use think\Exception;
  17. use think\exception\ErrorException;
  18. use think\facade\Db;
  19. use think\facade\Config;
  20. /**
  21. * Class Business
  22. * @package crmeb\command
  23. */
  24. class MakeAdmin extends Command
  25. {
  26. protected $stubList = [];
  27. private $after = [
  28. 'model' => '',
  29. 'services' => 'Services',
  30. 'validate' => 'Validate',
  31. 'controller' => '',
  32. ];
  33. private $deleteTimeField = 'delete_time';
  34. private $addTimeField = 'add_time';
  35. private $sortField = 'sort';
  36. /**
  37. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  38. */
  39. protected $intDateSuffix = ['time'];
  40. /**
  41. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  42. */
  43. protected $intListSuffix = ['images', 'ids', 'list'];
  44. protected function configure()
  45. {
  46. parent::configure();
  47. $this->setName('make')
  48. ->addOption('table', 't', Option::VALUE_REQUIRED, 'The name of the table to create')
  49. ->addOption('path', 'p', Option::VALUE_OPTIONAL, 'path', null)
  50. ->addOption('hidden', 'x', Option::VALUE_OPTIONAL, 'hidden fields', null)
  51. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force replace file', null)
  52. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files', null)
  53. ->addOption('sort', 's', Option::VALUE_OPTIONAL, 'sort field', null)
  54. ->setDescription('Create a new table class');
  55. }
  56. public function execute(Input $input, Output $output)
  57. {
  58. $table = $input->getOption('table') ?: '';
  59. if (!$table) {
  60. throw new Exception('Please enter the table name');
  61. }
  62. //自定义控制器
  63. $path = $input->getOption('path');
  64. $force = $input->getOption('force');
  65. $hidden = $input->getOption('hidden');
  66. $delete = $input->getOption('delete');
  67. $sortField = $input->getOption('sort');
  68. $hidden = str_replace(',', ',', $hidden);
  69. $hidden = explode(',', $hidden);
  70. array_push($hidden, $this->deleteTimeField);
  71. $connect = Db::connect('mysql');
  72. $dbname = Config::get('database.connections.mysql.database');
  73. $prefix = Config::get('database.connections.mysql.prefix');
  74. //检查主表
  75. $modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
  76. $modelTableType = 'table';
  77. $modelTableTypeName = $modelTableName = $modelName;
  78. $modelTableInfo = $connect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  79. if (!$modelTableInfo) {
  80. $modelTableType = 'name';
  81. $modelTableName = $prefix . $modelName;
  82. $modelTableInfo = $connect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  83. if (!$modelTableInfo) {
  84. throw new Exception("table not found");
  85. }
  86. }
  87. $modelTableInfo = $modelTableInfo[0];
  88. //模型
  89. list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($path, $table);
  90. list($serviceNamespace, $serviceName, $serviceFile, $serviceArr) = $this->getServicesData($path, $table);
  91. list($controllerNamespace, $controllerName, $controllerFile, $controllerArr, $controllerPath) = $this->getControllerData($path, $table);
  92. list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($path, $table);
  93. if ($delete) {
  94. $readyFiles = [$controllerFile, $modelFile, $validateFile, $serviceFile];
  95. foreach ($readyFiles as $k => $v) {
  96. $output->warning($v);
  97. }
  98. if (!$force) {
  99. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  100. $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
  101. if (trim($line) != 'yes') {
  102. throw new Exception("Operation is aborted!");
  103. }
  104. }
  105. foreach ($readyFiles as $k => $v) {
  106. if (file_exists($v)) {
  107. unlink($v);
  108. }
  109. //删除空文件夹
  110. switch ($v) {
  111. case $modelFile:
  112. $this->removeEmptyBaseDir($v, $modelArr);
  113. break;
  114. case $validateFile:
  115. $this->removeEmptyBaseDir($v, $validateArr);
  116. break;
  117. case $serviceArr:
  118. $this->removeEmptyBaseDir($v, $serviceArr);
  119. break;
  120. default:
  121. $this->removeEmptyBaseDir($v, $controllerArr);
  122. }
  123. }
  124. $output->info("Delete Successed");
  125. return;
  126. }
  127. //非覆盖模式时如果存在控制器文件则报错
  128. if (is_file($controllerFile) && !$force) {
  129. throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  130. }
  131. //非覆盖模式时如果存在模型文件则报错
  132. if (is_file($modelFile) && !$force) {
  133. throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  134. }
  135. //非覆盖模式时如果存在验证文件则报错
  136. if (is_file($serviceFile) && !$force) {
  137. throw new Exception("services already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  138. }
  139. //非覆盖模式时如果存在验证文件则报错
  140. if (is_file($validateFile) && !$force) {
  141. throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  142. }
  143. //从数据库中获取表字段信息
  144. $sql = "SELECT * FROM `information_schema`.`columns` "
  145. . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  146. . "ORDER BY ORDINAL_POSITION";
  147. //加载主表的列
  148. $columnList = $connect->query($sql, [$dbname, $modelTableName]);
  149. $fieldArr = [];
  150. $priKeyArr = [];
  151. foreach ($columnList as $k => $v) {
  152. $fieldArr[] = $v['COLUMN_NAME'];
  153. if ($v['COLUMN_KEY'] == 'PRI') {
  154. $priKeyArr[] = $v['COLUMN_NAME'];
  155. }
  156. }
  157. if (!$priKeyArr) {
  158. throw new Exception('Primary key not found!');
  159. }
  160. if (count($priKeyArr) > 1) {
  161. throw new Exception('Multiple primary key not support!');
  162. }
  163. $priKey = reset($priKeyArr);
  164. try {
  165. $setAttrArr = [];
  166. $getAttrArr = [];
  167. $getEnumArr = [];
  168. $hiddenArr = [];
  169. $appendAttrList = [];
  170. $exportAttr = [];
  171. $validateRules = [];
  172. $searchAttr = [];
  173. $searchFieldAttr = [];
  174. $validateMessage = [];
  175. $createParams = [];
  176. $order = '';
  177. //循环所有字段,开始构造视图的HTML和JS信息
  178. foreach ($columnList as $k => $v) {
  179. $field = $v['COLUMN_NAME'];
  180. $itemArr = [];
  181. // 这里构建Enum和Set类型的列表数据
  182. if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
  183. if ($v['DATA_TYPE'] !== 'tinyint') {
  184. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  185. $itemArr = explode(',', str_replace("'", '', $itemArr));
  186. }
  187. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  188. //如果类型为tinyint且有使用备注数据
  189. if ($itemArr && !in_array($v['DATA_TYPE'], ['enum', 'set'])) {
  190. $v['DATA_TYPE'] = 'enum';
  191. }
  192. }
  193. // 语言列表
  194. $langList = [];
  195. if ($v['COLUMN_COMMENT'] != '') {
  196. $langList = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  197. }
  198. if (in_array($field, $hidden)) {
  199. $this->hiddenAttr($hiddenArr, $field);
  200. }
  201. if ($v['COLUMN_KEY'] == 'PRI')
  202. $exportAttr[$field] = $langList[$field] ?? parseName($field, 1);
  203. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $hidden)) {
  204. if ($field == $this->addTimeField) {
  205. if ($v['DATA_TYPE'] == 'int') {
  206. $this->getAttr($getAttrArr, $field, 'add_time');
  207. } else {
  208. $this->getAttr($getAttrArr, $field, 'add_time_datetime');
  209. }
  210. $this->searchAttr($searchFieldAttr, 'time');
  211. $exportAttr[$field] = $langList[$field] ?? '添加时间';
  212. } else if ($sortField && $field == $sortField || !$sortField && $field == $this->sortField) {
  213. $exportAttr[$field] = $langList[$field] ?? '排序';
  214. $order = 'protected $order = ' . "'{$field} desc,{$priKey} desc';";
  215. } else {
  216. $inputType = $this->getFieldType($v);
  217. // 如果默认值非null,则是一个必选项
  218. if ($inputType == 'select') {
  219. $this->getEnum($getEnumArr, $field, $itemArr, $langList);
  220. //添加一个获取器
  221. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  222. if ($v['DATA_TYPE'] == 'set') {
  223. $this->setAttr($setAttrArr, $field, $inputType);
  224. }
  225. $this->setCreate($createParams, $v);
  226. $this->appendAttr($appendAttrList, $field);
  227. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  228. } else if ($inputType == 'list') {
  229. $this->getAttr($getAttrArr, $field, $inputType);
  230. $this->setAttr($setAttrArr, $field, $inputType);
  231. $this->setCreate($createParams, $v);
  232. $this->appendAttr($appendAttrList, $field);
  233. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  234. } elseif ($inputType == 'datetime') {
  235. $this->getAttr($getAttrArr, $field, $inputType);
  236. $this->setAttr($setAttrArr, $field, $inputType);
  237. $this->setCreate($createParams, $v);
  238. $this->appendAttr($appendAttrList, $field);
  239. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  240. } else {
  241. $this->setCreate($createParams, $v);
  242. $exportAttr[$field] = $langList[$field] ?? parseName($field, 1);
  243. }
  244. $this->checkValidate($validateRules, $validateMessage, $v, $field, $langList[$field] ?? parseName($field, 1), $itemArr);
  245. $this->searchAttrHandel($searchAttr, $searchFieldAttr, $field, $langList[$field] ?? parseName($field, 1), $inputType);
  246. }
  247. }
  248. }
  249. //表注释
  250. $tableComment = $modelTableInfo ? $modelTableInfo['Comment'] : '';
  251. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) : $tableComment;
  252. $data = [
  253. 'table' => $table,
  254. 'tableComment' => $tableComment,
  255. 'tableName' => $modelTableName,
  256. 'resourceName' => $table,
  257. 'path' => $controllerPath,
  258. 'pk' => $priKey,
  259. 'controllerNamespace' => $controllerNamespace,
  260. 'controllerName' => $controllerName,
  261. 'modelNamespace' => $modelNamespace,
  262. 'modelName' => $modelName,
  263. 'validateNamespace' => $validateNamespace,
  264. 'validateName' => $validateName,
  265. 'servicesNamespace' => $serviceNamespace,
  266. 'servicesName' => $serviceName,
  267. 'modelTableName' => $modelTableName,
  268. 'modelTableType' => $modelTableType,
  269. 'modelTableTypeName' => $modelTableTypeName,
  270. 'softDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use think\model\concern\SoftDelete;" : '',
  271. 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  272. 'hiddenArrList' => implode(",\n\t", $hiddenArr),
  273. 'appendAttrList' => implode(",\n\t", $appendAttrList),
  274. 'getEnumList' => implode("\n\n", $getEnumArr),
  275. 'getAttrList' => implode("\n\n", $getAttrArr),
  276. 'setAttrList' => implode("\n\n", $setAttrArr),
  277. 'validateRules' => implode(",\n", $this->handelArrayDate($validateRules)),
  278. 'validateMessage' => implode(",\n", $this->handelArrayDate($validateMessage)),
  279. 'exportAttrList' => implode(",\n", $this->handelArrayDate($exportAttr)),
  280. 'createParams' => implode(",\n\t", $createParams),
  281. 'searchFieldAttr' => implode(",\n\t", $searchFieldAttr),
  282. 'searchAttrList' => implode("\n\n", $searchAttr),
  283. 'order' => $order
  284. ];
  285. // 生成控制器文件
  286. $this->writeToFile('controller', $data, $controllerFile);
  287. // 生成服务文件
  288. $this->writeToFile('services', $data, $serviceFile);
  289. // 生成模型文件
  290. $this->writeToFile('model', $data, $modelFile);
  291. // 生成验证文件
  292. $this->writeToFile('validate', $data, $validateFile);
  293. $output->info('Create Successed');
  294. } catch (ErrorException $e) {
  295. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  296. }
  297. }
  298. /**
  299. * 移除相对的空目录
  300. * @param $parseFile
  301. * @param $parseArr
  302. * @return bool
  303. */
  304. protected function removeEmptyBaseDir($parseFile, $parseArr)
  305. {
  306. if (count($parseArr) > 1) {
  307. $parentDir = dirname($parseFile);
  308. for ($i = 0; $i < count($parseArr); $i++) {
  309. try {
  310. $iterator = new \FilesystemIterator($parentDir);
  311. $isDirEmpty = !$iterator->valid();
  312. if ($isDirEmpty) {
  313. rmdir($parentDir);
  314. $parentDir = dirname($parentDir);
  315. } else {
  316. return true;
  317. }
  318. } catch (\UnexpectedValueException $e) {
  319. return false;
  320. }
  321. }
  322. }
  323. return true;
  324. }
  325. protected function setCreate(&$createParams, $item)
  326. {
  327. $field = $item['COLUMN_NAME'];
  328. $type = $item['DATA_TYPE'];
  329. if ($type == 'set' || $this->isMatchSuffix($field, $this->intListSuffix)) {
  330. $createParams[] = <<<EOD
  331. ['{$field}', []]
  332. EOD;
  333. } else if (in_array($type, ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'decimal', 'double', 'float']) && !$this->isMatchSuffix($field, $this->intDateSuffix)) {
  334. $default = !($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null') ? $item['COLUMN_DEFAULT'] : 0;
  335. $createParams[] = <<<EOD
  336. ['{$field}', {$default}]
  337. EOD;
  338. } else {
  339. $default = !($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null') ? $item['COLUMN_DEFAULT'] : '';
  340. $createParams[] = <<<EOD
  341. ['{$field}', '{$default}']
  342. EOD;
  343. }
  344. }
  345. protected function checkValidate(&$validateArr, &$validateMessage, $item, $field, $fieldName, $itemArr = [])
  346. {
  347. if (empty($validateArr[$field]))
  348. $validateArr[$field] = [];
  349. // 如果默认值非null,则是一个必选项
  350. if ($item['IS_NULLABLE'] == 'NO' && ($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null')) {
  351. $validateArr[$field][] = 'require';
  352. $validateMessage[$field . '.require'] = $fieldName . '是必需的';
  353. }
  354. if ($itemArr) {
  355. $list = [];
  356. foreach ($itemArr as $k => $v) {
  357. $list[] = $k;
  358. }
  359. $validateArr[$field][] = 'in:' . implode(',', $list);
  360. $validateMessage[$field . '.in'] = '请选择正确的' . $fieldName;
  361. }
  362. if ($item['DATA_TYPE'] == 'set' || $this->isMatchSuffix($field, $this->intListSuffix)) {
  363. $validateArr[$field][] = 'array';
  364. $validateMessage[$field . '.array'] = $fieldName . '必须是数组';
  365. }
  366. if (in_array($item['DATA_TYPE'], ['bigint', 'int', 'mediumint', 'smallint', 'tinyint']) && !$this->isMatchSuffix($field, $this->intDateSuffix)) {
  367. $validateArr[$field][] = 'number';
  368. $validateMessage[$field . '.number'] = $fieldName . '必须是整数';
  369. }
  370. if (in_array($item['DATA_TYPE'], ['decimal', 'double', 'float'])) {
  371. $validateArr[$field][] = 'float';
  372. $validateMessage[$field . '.float'] = $fieldName . '必须是数字';
  373. }
  374. if (stripos($item['COLUMN_TYPE'], 'unsigned') !== false) {
  375. $validateArr[$field][] = 'egt:0';
  376. $validateMessage[$field . '.egt'] = $fieldName . '大于等于0';
  377. }
  378. if ($this->isMatchSuffix($field, ['phone', 'mobile'])) {
  379. $validateArr[$field][] = 'mobile';
  380. $validateMessage[$field . '.mobile'] = $fieldName . '不是有效的手机号码';
  381. }
  382. if ($this->isMatchSuffix($field, ['email'])) {
  383. $validateArr[$field][] = 'email';
  384. $validateMessage[$field . '.email'] = $fieldName . '不是有效的邮箱地址';
  385. }
  386. if ($this->isMatchSuffix($field, ['url', 'link'])) {
  387. $validateArr[$field][] = 'url';
  388. $validateMessage[$field . '.url'] = $fieldName . '不是有效的url';
  389. }
  390. }
  391. protected function handelArrayDate($validate)
  392. {
  393. $res = [];
  394. foreach ($validate as $k => $v) {
  395. if (!empty($v)) {
  396. if (is_array($v)) $v = implode('|', $v);
  397. $res[] = <<<EOD
  398. '{$k}' => '{$v}'
  399. EOD;
  400. }
  401. }
  402. return $res;
  403. }
  404. /**
  405. * 写入到文件
  406. * @param string $name
  407. * @param array $data
  408. * @param string $pathname
  409. * @return mixed
  410. */
  411. protected function writeToFile($name, $data, $pathname)
  412. {
  413. foreach ($data as $index => &$datum) {
  414. $datum = is_array($datum) ? '' : $datum;
  415. }
  416. unset($datum);
  417. $content = $this->getReplacedStub($name, $data);
  418. if (!is_dir(dirname($pathname))) {
  419. mkdir(dirname($pathname), 0755, true);
  420. }
  421. return file_put_contents($pathname, $content);
  422. }
  423. protected function getLangItem($field, $content)
  424. {
  425. $content = str_replace(',', ',', $content);
  426. if (stripos($content, ':') !== false && stripos($content, '=') !== false) {
  427. list($fieldLang, $item) = explode(':', $content);
  428. $itemArr = [$field => $fieldLang];
  429. foreach (explode(',', $item) as $k => $v) {
  430. $valArr = explode('=', $v);
  431. if (count($valArr) == 2) {
  432. list($key, $value) = $valArr;
  433. $itemArr[$field . ' ' . $key] = $value;
  434. }
  435. }
  436. } else {
  437. $itemArr = [$field => $content];
  438. }
  439. return $itemArr;
  440. }
  441. protected function getEnum(&$getEnum, $field, $itemArr = [], $langList = [])
  442. {
  443. $fieldList = $this->getFieldListName($field);
  444. $methodName = 'get' . ucfirst($fieldList);
  445. foreach ($itemArr as $k => &$v) {
  446. $v = $langList[$v] ?? '未知';
  447. }
  448. unset($v);
  449. $itemString = $this->getArrayString($itemArr);
  450. $getEnum[] = <<<EOD
  451. public function {$methodName}()
  452. {
  453. return [{$itemString}];
  454. }
  455. EOD;
  456. }
  457. /**
  458. * 将数据转换成带字符串
  459. * @param mixed $arr
  460. * @return string
  461. */
  462. protected function getArrayString($arr)
  463. {
  464. if (!is_array($arr)) {
  465. return $arr;
  466. }
  467. $stringArr = [];
  468. foreach ($arr as $k => $v) {
  469. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  470. if (!$is_var) {
  471. $v = str_replace("'", "\'", $v);
  472. $k = str_replace("'", "\'", $k);
  473. }
  474. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  475. }
  476. return implode(", ", $stringArr);
  477. }
  478. protected function setAttr(&$setAttr, $field, $inputType = '')
  479. {
  480. if (!in_array($inputType, ['datetime', 'select', 'list'])) {
  481. return;
  482. }
  483. $return = <<<EOD
  484. return \$value;
  485. EOD;
  486. $attrField = ucfirst($this->getCamelizeName($field));
  487. if ($inputType == 'datetime') {
  488. $return = <<<EOD
  489. return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  490. EOD;
  491. } elseif ($inputType == 'select' || $inputType == 'list') {
  492. $return = <<<EOD
  493. return is_array(\$value) ? implode(',', \$value) : \$value;
  494. EOD;
  495. }
  496. $setAttr[] = <<<EOD
  497. protected function set{$attrField}Attr(\$value)
  498. {
  499. $return
  500. }
  501. EOD;
  502. }
  503. protected function appendAttr(&$appendAttrList, $field)
  504. {
  505. $appendAttrList[] = <<<EOD
  506. '{$field}_chs'
  507. EOD;
  508. }
  509. protected function hiddenAttr(&$hiddenAttrList, $field)
  510. {
  511. $hiddenAttrList[] = <<<EOD
  512. '{$field}'
  513. EOD;
  514. }
  515. protected function searchAttr(&$searchFieldAttr, $field)
  516. {
  517. $searchFieldAttr[] = <<<EOD
  518. ['{$field}', '']
  519. EOD;
  520. }
  521. protected function getFieldListName($field)
  522. {
  523. return $this->getCamelizeName($field) . 'List';
  524. }
  525. protected function getCamelizeName($uncamelized_words, $separator = '_')
  526. {
  527. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  528. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  529. }
  530. protected function getAttr(&$getAttr, $field, $inputType = '')
  531. {
  532. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'add_time', 'add_time_datetime', 'list'])) {
  533. return;
  534. }
  535. $attrField = ucfirst($this->getCamelizeName($field));
  536. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}ChsAttr", 'listMethodName' => "get{$attrField}List"]);
  537. }
  538. protected function searchAttrHandel(&$searchAttr, &$searchFieldAttr, $field, $fieldName, $inputType = '')
  539. {
  540. $type = 'default';
  541. if ($this->isMatchSuffix($field, ['id'])) {
  542. $type = 'id';
  543. } else if ($this->isMatchSuffix($field, ['name', 'title', 'info'])) {
  544. $type = 'like';
  545. } else if (in_array($inputType, ['datetime'])) {
  546. $type = 'time';
  547. } else if (in_array($inputType, ['multiple', 'list'])) {
  548. $type = 'find_in_set';
  549. } else if (in_array($inputType, ['select'])) {
  550. $type = 'default';
  551. } else {
  552. return;
  553. }
  554. $attrField = ucfirst($this->getCamelizeName($field));
  555. $searchAttr[] = $this->getReplacedStub("search" . DS . $type, ['field' => $field, 'fieldName' => $fieldName, 'methodName' => "search{$attrField}Attr"]);
  556. $this->searchAttr($searchFieldAttr, $field);
  557. }
  558. /**
  559. * 获取替换后的数据
  560. * @param string $name
  561. * @param array $data
  562. * @return string
  563. */
  564. protected function getReplacedStub($name, $data)
  565. {
  566. foreach ($data as $index => &$datum) {
  567. $datum = is_array($datum) ? '' : $datum;
  568. }
  569. unset($datum);
  570. $search = $replace = [];
  571. foreach ($data as $k => $v) {
  572. $search[] = "{%{$k}%}";
  573. $replace[] = $v;
  574. }
  575. $stubname = $this->getStub($name);
  576. if (isset($this->stubList[$stubname])) {
  577. $stub = $this->stubList[$stubname];
  578. } else {
  579. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  580. }
  581. $content = str_replace($search, $replace, $stub);
  582. return $content;
  583. }
  584. /**
  585. * 获取基础模板
  586. * @param string $name
  587. * @return string
  588. */
  589. protected function getStub($name)
  590. {
  591. return __DIR__ . DS . 'stubs' . DS . $name . '.stub';
  592. }
  593. protected function getFieldType(&$v)
  594. {
  595. $inputType = 'text';
  596. switch ($v['DATA_TYPE']) {
  597. case 'enum':
  598. case 'set':
  599. $inputType = 'select';
  600. break;
  601. case 'year':
  602. case 'date':
  603. case 'time':
  604. case 'datetime':
  605. case 'timestamp':
  606. $inputType = 'datetime';
  607. break;
  608. default:
  609. break;
  610. }
  611. $fieldsName = $v['COLUMN_NAME'];
  612. // 指定后缀说明也是个时间字段
  613. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  614. $inputType = 'datetime';
  615. }
  616. // 指定后缀结尾且类型为enum,说明是个单选框
  617. if ($this->isMatchSuffix($fieldsName, $this->intListSuffix)) {
  618. $inputType = "list";
  619. }
  620. return $inputType;
  621. }
  622. /**
  623. * 判断是否符合指定后缀
  624. * @param string $field 字段名称
  625. * @param mixed $suffixArr 后缀
  626. * @return boolean
  627. */
  628. protected function isMatchSuffix($field, $suffixArr)
  629. {
  630. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  631. foreach ($suffixArr as $k => $v) {
  632. if (preg_match("/{$v}$/i", $field)) {
  633. return true;
  634. }
  635. }
  636. return false;
  637. }
  638. /**
  639. * 获取模型相关信息
  640. * @param $module
  641. * @param $model
  642. * @param $table
  643. * @return array
  644. */
  645. protected function getModelData($path, $table)
  646. {
  647. return $this->getParseNameData($path, $table, 'model');
  648. }
  649. /**
  650. * 获取模型相关信息
  651. * @param $module
  652. * @param $model
  653. * @param $table
  654. * @return array
  655. */
  656. protected function getServicesData($path, $table)
  657. {
  658. return $this->getParseNameData($path, $table, 'services');
  659. }
  660. /**
  661. * 获取模型相关信息
  662. * @param $module
  663. * @param $model
  664. * @param $table
  665. * @return array
  666. */
  667. protected function getValidateData($path, $table)
  668. {
  669. return $this->getParseNameData($path, $table, 'validate');
  670. }
  671. protected function getControllerData($path, $table)
  672. {
  673. return $this->getParseNameData($path, $table, 'controller');
  674. }
  675. /**
  676. * 获取已解析相关信息
  677. * @param string $name 自定义名称
  678. * @param string $table 数据表名
  679. * @param string $type 解析类型,本例中为controller、model、validate
  680. * @return array
  681. */
  682. protected function getParseNameData($path, $table, $type)
  683. {
  684. $parseName = parseName($table, 1);
  685. $parseName = $parseName . $this->after[$type];
  686. if (!$path) {
  687. $path = str_replace('_', '/', $table);
  688. $path = str_replace(['.', '/', '\\'], '/', $path);
  689. $arr = explode('/', $path);
  690. array_pop($arr);
  691. } else {
  692. $path = str_replace(['.', '/', '\\'], '/', $path);
  693. $arr = explode('/', $path);
  694. }
  695. $parseArr = $arr;
  696. array_push($parseArr, $parseName);
  697. $appNamespace = Config::get('app.app_namespace');
  698. $parseNamespace = "{$appNamespace}\\{$type}" . (in_array($type, ['controller', 'validate']) ? '\\admin' : '') . ($arr ? "\\" . implode("\\", $arr) : "");
  699. $moduleDir = $this->app->getRootPath() . 'app' . DS . $type . DS . ((in_array($type, ['controller', 'validate']) ? 'admin' : '') . DS);
  700. $parseFile = $moduleDir . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  701. return [$parseNamespace, $parseName, $parseFile, $parseArr, ($arr ? implode('.', $arr) . '.' : '')];
  702. }
  703. protected function getItemArray($item, $field, $comment)
  704. {
  705. $itemArr = [];
  706. $comment = str_replace(',', ',', $comment);
  707. if (stripos($comment, ':') !== false && stripos($comment, '=') !== false) {
  708. list($fieldLang, $item) = explode(':', $comment);
  709. $itemArr = [];
  710. foreach (explode(',', $item) as $k => $v) {
  711. $valArr = explode('=', $v);
  712. if (count($valArr) == 2) {
  713. list($key, $value) = $valArr;
  714. $itemArr[$key] = $field . ' ' . $key;
  715. }
  716. }
  717. } else {
  718. foreach ($item as $k => $v) {
  719. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  720. }
  721. }
  722. return $itemArr;
  723. }
  724. }