MakeAdmin.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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, $resourceName) = $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' => $resourceName,
  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. } catch (ErrorException $e) {
  294. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  295. }
  296. }
  297. /**
  298. * 移除相对的空目录
  299. * @param $parseFile
  300. * @param $parseArr
  301. * @return bool
  302. */
  303. protected function removeEmptyBaseDir($parseFile, $parseArr)
  304. {
  305. if (count($parseArr) > 1) {
  306. $parentDir = dirname($parseFile);
  307. for ($i = 0; $i < count($parseArr); $i++) {
  308. try {
  309. $iterator = new \FilesystemIterator($parentDir);
  310. $isDirEmpty = !$iterator->valid();
  311. if ($isDirEmpty) {
  312. rmdir($parentDir);
  313. $parentDir = dirname($parentDir);
  314. } else {
  315. return true;
  316. }
  317. } catch (\UnexpectedValueException $e) {
  318. return false;
  319. }
  320. }
  321. }
  322. return true;
  323. }
  324. protected function setCreate(&$createParams, $item)
  325. {
  326. $field = $item['COLUMN_NAME'];
  327. $type = $item['DATA_TYPE'];
  328. if ($type == 'set' || $this->isMatchSuffix($field, $this->intListSuffix)) {
  329. $createParams[] = <<<EOD
  330. ['{$field}', []]
  331. EOD;
  332. } else if (in_array($type, ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'decimal', 'double', 'float']) && !$this->isMatchSuffix($field, $this->intDateSuffix)) {
  333. $default = !($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null') ? $item['COLUMN_DEFAULT'] : 0;
  334. $createParams[] = <<<EOD
  335. ['{$field}', {$default}]
  336. EOD;
  337. } else {
  338. $default = !($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null') ? $item['COLUMN_DEFAULT'] : '';
  339. $createParams[] = <<<EOD
  340. ['{$field}', '{$default}']
  341. EOD;
  342. }
  343. }
  344. protected function checkValidate(&$validateArr, &$validateMessage, $item, $field, $fieldName, $itemArr = [])
  345. {
  346. if (empty($validateArr[$field]))
  347. $validateArr[$field] = [];
  348. // 如果默认值非null,则是一个必选项
  349. if ($item['IS_NULLABLE'] == 'NO' && ($item['COLUMN_DEFAULT'] == '' || $item['COLUMN_DEFAULT'] == 'null')) {
  350. $validateArr[$field][] = 'require';
  351. $validateMessage[$field . '.require'] = $fieldName . '是必需的';
  352. }
  353. if ($itemArr) {
  354. $list = [];
  355. foreach ($itemArr as $k => $v) {
  356. $list[] = $k;
  357. }
  358. $validateArr[$field][] = 'in:' . implode(',', $list);
  359. $validateMessage[$field . '.in'] = '请选择正确的' . $fieldName;
  360. }
  361. if ($item['DATA_TYPE'] == 'set' || $this->isMatchSuffix($field, $this->intListSuffix)) {
  362. $validateArr[$field][] = 'array';
  363. $validateMessage[$field . '.array'] = $fieldName . '必须是数组';
  364. }
  365. if (in_array($item['DATA_TYPE'], ['bigint', 'int', 'mediumint', 'smallint', 'tinyint']) && !$this->isMatchSuffix($field, $this->intDateSuffix)) {
  366. $validateArr[$field][] = 'number';
  367. $validateMessage[$field . '.number'] = $fieldName . '必须是整数';
  368. }
  369. if (in_array($item['DATA_TYPE'], ['decimal', 'double', 'float'])) {
  370. $validateArr[$field][] = 'float';
  371. $validateMessage[$field . '.float'] = $fieldName . '必须是数字';
  372. }
  373. if (stripos($item['COLUMN_TYPE'], 'unsigned') !== false) {
  374. $validateArr[$field][] = 'egt:0';
  375. $validateMessage[$field . '.egt'] = $fieldName . '大于等于0';
  376. }
  377. if ($this->isMatchSuffix($field, ['phone', 'mobile'])) {
  378. $validateArr[$field][] = 'mobile';
  379. $validateMessage[$field . '.mobile'] = $fieldName . '不是有效的手机号码';
  380. }
  381. if ($this->isMatchSuffix($field, ['email'])) {
  382. $validateArr[$field][] = 'email';
  383. $validateMessage[$field . '.email'] = $fieldName . '不是有效的邮箱地址';
  384. }
  385. if ($this->isMatchSuffix($field, ['url', 'link'])) {
  386. $validateArr[$field][] = 'url';
  387. $validateMessage[$field . '.url'] = $fieldName . '不是有效的url';
  388. }
  389. }
  390. protected function handelArrayDate($validate)
  391. {
  392. $res = [];
  393. foreach ($validate as $k => $v) {
  394. if (!empty($v)) {
  395. if (is_array($v)) $v = implode('|', $v);
  396. $res[] = <<<EOD
  397. '{$k}' => '{$v}'
  398. EOD;
  399. }
  400. }
  401. return $res;
  402. }
  403. /**
  404. * 写入到文件
  405. * @param string $name
  406. * @param array $data
  407. * @param string $pathname
  408. * @return mixed
  409. */
  410. protected function writeToFile($name, $data, $pathname)
  411. {
  412. foreach ($data as $index => &$datum) {
  413. $datum = is_array($datum) ? '' : $datum;
  414. }
  415. unset($datum);
  416. $content = $this->getReplacedStub($name, $data);
  417. if (!is_dir(dirname($pathname))) {
  418. mkdir(dirname($pathname), 0755, true);
  419. }
  420. return file_put_contents($pathname, $content);
  421. }
  422. protected function getLangItem($field, $content)
  423. {
  424. $content = str_replace(',', ',', $content);
  425. if (stripos($content, ':') !== false && stripos($content, '=') !== false) {
  426. list($fieldLang, $item) = explode(':', $content);
  427. $itemArr = [$field => $fieldLang];
  428. foreach (explode(',', $item) as $k => $v) {
  429. $valArr = explode('=', $v);
  430. if (count($valArr) == 2) {
  431. list($key, $value) = $valArr;
  432. $itemArr[$field . ' ' . $key] = $value;
  433. }
  434. }
  435. } else {
  436. $itemArr = [$field => $content];
  437. }
  438. return $itemArr;
  439. }
  440. protected function getEnum(&$getEnum, $field, $itemArr = [], $langList = [])
  441. {
  442. $fieldList = $this->getFieldListName($field);
  443. $methodName = 'get' . ucfirst($fieldList);
  444. foreach ($itemArr as $k => &$v) {
  445. $v = $langList[$v] ?? '未知';
  446. }
  447. unset($v);
  448. $itemString = $this->getArrayString($itemArr);
  449. $getEnum[] = <<<EOD
  450. public function {$methodName}()
  451. {
  452. return [{$itemString}];
  453. }
  454. EOD;
  455. }
  456. /**
  457. * 将数据转换成带字符串
  458. * @param mixed $arr
  459. * @return string
  460. */
  461. protected function getArrayString($arr)
  462. {
  463. if (!is_array($arr)) {
  464. return $arr;
  465. }
  466. $stringArr = [];
  467. foreach ($arr as $k => $v) {
  468. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  469. if (!$is_var) {
  470. $v = str_replace("'", "\'", $v);
  471. $k = str_replace("'", "\'", $k);
  472. }
  473. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  474. }
  475. return implode(", ", $stringArr);
  476. }
  477. protected function setAttr(&$setAttr, $field, $inputType = '')
  478. {
  479. if (!in_array($inputType, ['datetime', 'select', 'list'])) {
  480. return;
  481. }
  482. $return = <<<EOD
  483. return \$value;
  484. EOD;
  485. $attrField = ucfirst($this->getCamelizeName($field));
  486. if ($inputType == 'datetime') {
  487. $return = <<<EOD
  488. return \$value === '' ? null : (\$value && !is_numeric(\$value) ? strtotime(\$value) : \$value);
  489. EOD;
  490. } elseif ($inputType == 'select' || $inputType == 'list') {
  491. $return = <<<EOD
  492. return is_array(\$value) ? implode(',', \$value) : \$value;
  493. EOD;
  494. }
  495. $setAttr[] = <<<EOD
  496. protected function set{$attrField}Attr(\$value)
  497. {
  498. $return
  499. }
  500. EOD;
  501. }
  502. protected function appendAttr(&$appendAttrList, $field)
  503. {
  504. $appendAttrList[] = <<<EOD
  505. '{$field}_chs'
  506. EOD;
  507. }
  508. protected function hiddenAttr(&$hiddenAttrList, $field)
  509. {
  510. $hiddenAttrList[] = <<<EOD
  511. '{$field}'
  512. EOD;
  513. }
  514. protected function searchAttr(&$searchFieldAttr, $field)
  515. {
  516. $searchFieldAttr[] = <<<EOD
  517. ['{$field}', '']
  518. EOD;
  519. }
  520. protected function getFieldListName($field)
  521. {
  522. return $this->getCamelizeName($field) . 'List';
  523. }
  524. protected function getCamelizeName($uncamelized_words, $separator = '_')
  525. {
  526. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  527. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  528. }
  529. protected function getAttr(&$getAttr, $field, $inputType = '')
  530. {
  531. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'add_time', 'add_time_datetime', 'list'])) {
  532. return;
  533. }
  534. $attrField = ucfirst($this->getCamelizeName($field));
  535. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}ChsAttr", 'listMethodName' => "get{$attrField}List"]);
  536. }
  537. protected function searchAttrHandel(&$searchAttr, &$searchFieldAttr, $field, $fieldName, $inputType = '')
  538. {
  539. $type = 'default';
  540. if ($this->isMatchSuffix($field, ['id'])) {
  541. $type = 'id';
  542. } else if ($this->isMatchSuffix($field, ['name', 'title', 'info'])) {
  543. $type = 'like';
  544. } else if (in_array($inputType, ['datetime'])) {
  545. $type = 'time';
  546. } else if (in_array($inputType, ['multiple', 'list'])) {
  547. $type = 'find_in_set';
  548. } else if (in_array($inputType, ['select'])) {
  549. $type = 'default';
  550. } else {
  551. return;
  552. }
  553. $attrField = ucfirst($this->getCamelizeName($field));
  554. $searchAttr[] = $this->getReplacedStub("search" . DS . $type, ['field' => $field, 'fieldName' => $fieldName, 'methodName' => "search{$attrField}Attr"]);
  555. $this->searchAttr($searchFieldAttr, $field);
  556. }
  557. /**
  558. * 获取替换后的数据
  559. * @param string $name
  560. * @param array $data
  561. * @return string
  562. */
  563. protected function getReplacedStub($name, $data)
  564. {
  565. foreach ($data as $index => &$datum) {
  566. $datum = is_array($datum) ? '' : $datum;
  567. }
  568. unset($datum);
  569. $search = $replace = [];
  570. foreach ($data as $k => $v) {
  571. $search[] = "{%{$k}%}";
  572. $replace[] = $v;
  573. }
  574. $stubname = $this->getStub($name);
  575. if (isset($this->stubList[$stubname])) {
  576. $stub = $this->stubList[$stubname];
  577. } else {
  578. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  579. }
  580. $content = str_replace($search, $replace, $stub);
  581. return $content;
  582. }
  583. /**
  584. * 获取基础模板
  585. * @param string $name
  586. * @return string
  587. */
  588. protected function getStub($name)
  589. {
  590. return __DIR__ . DS . 'stubs' . DS . $name . '.stub';
  591. }
  592. protected function getFieldType(&$v)
  593. {
  594. $inputType = 'text';
  595. switch ($v['DATA_TYPE']) {
  596. case 'enum':
  597. case 'set':
  598. $inputType = 'select';
  599. break;
  600. case 'year':
  601. case 'date':
  602. case 'time':
  603. case 'datetime':
  604. case 'timestamp':
  605. $inputType = 'datetime';
  606. break;
  607. default:
  608. break;
  609. }
  610. $fieldsName = $v['COLUMN_NAME'];
  611. // 指定后缀说明也是个时间字段
  612. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix)) {
  613. $inputType = 'datetime';
  614. }
  615. // 指定后缀结尾且类型为enum,说明是个单选框
  616. if ($this->isMatchSuffix($fieldsName, $this->intListSuffix)) {
  617. $inputType = "list";
  618. }
  619. return $inputType;
  620. }
  621. /**
  622. * 判断是否符合指定后缀
  623. * @param string $field 字段名称
  624. * @param mixed $suffixArr 后缀
  625. * @return boolean
  626. */
  627. protected function isMatchSuffix($field, $suffixArr)
  628. {
  629. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  630. foreach ($suffixArr as $k => $v) {
  631. if (preg_match("/{$v}$/i", $field)) {
  632. return true;
  633. }
  634. }
  635. return false;
  636. }
  637. /**
  638. * 获取模型相关信息
  639. * @param $module
  640. * @param $model
  641. * @param $table
  642. * @return array
  643. */
  644. protected function getModelData($path, $table)
  645. {
  646. return $this->getParseNameData($path, $table, 'model');
  647. }
  648. /**
  649. * 获取模型相关信息
  650. * @param $module
  651. * @param $model
  652. * @param $table
  653. * @return array
  654. */
  655. protected function getServicesData($path, $table)
  656. {
  657. return $this->getParseNameData($path, $table, 'services');
  658. }
  659. /**
  660. * 获取模型相关信息
  661. * @param $module
  662. * @param $model
  663. * @param $table
  664. * @return array
  665. */
  666. protected function getValidateData($path, $table)
  667. {
  668. return $this->getParseNameData($path, $table, 'validate');
  669. }
  670. protected function getControllerData($path, $table)
  671. {
  672. return $this->getParseNameData($path, $table, 'controller');
  673. }
  674. /**
  675. * 获取已解析相关信息
  676. * @param string $name 自定义名称
  677. * @param string $table 数据表名
  678. * @param string $type 解析类型,本例中为controller、model、validate
  679. * @return array
  680. */
  681. protected function getParseNameData($path, $table, $type)
  682. {
  683. $parseName = parseName($table, 1);
  684. $parseName = $parseName . $this->after[$type];
  685. if (!$path) {
  686. $path = str_replace('_', '/', $table);
  687. $path = str_replace(['.', '/', '\\'], '/', $path);
  688. $arr = explode('/', $path);
  689. array_pop($arr);
  690. } else {
  691. $path = str_replace(['.', '/', '\\'], '/', $path);
  692. $arr = explode('/', $path);
  693. }
  694. $resourceName = $table;
  695. foreach ($arr as $v) {
  696. if (strpos($resourceName, $v . '_') === 0) {
  697. $resourceName = substr($resourceName, strlen($v . '_'));
  698. }
  699. }
  700. $parseArr = $arr;
  701. array_push($parseArr, $parseName);
  702. $appNamespace = Config::get('app.app_namespace');
  703. $parseNamespace = "{$appNamespace}\\{$type}" . (in_array($type, ['controller', 'validate']) ? '\\admin' : '') . ($arr ? "\\" . implode("\\", $arr) : "");
  704. $moduleDir = $this->app->getRootPath() . 'app' . DS . $type . DS . ((in_array($type, ['controller', 'validate']) ? 'admin' : '') . DS);
  705. $parseFile = $moduleDir . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  706. return [$parseNamespace, $parseName, $parseFile, $parseArr, ($arr ? implode('.', $arr) . '.' : ''), $resourceName];
  707. }
  708. protected function getItemArray($item, $field, $comment)
  709. {
  710. $itemArr = [];
  711. $comment = str_replace(',', ',', $comment);
  712. if (stripos($comment, ':') !== false && stripos($comment, '=') !== false) {
  713. list($fieldLang, $item) = explode(':', $comment);
  714. $itemArr = [];
  715. foreach (explode(',', $item) as $k => $v) {
  716. $valArr = explode('=', $v);
  717. if (count($valArr) == 2) {
  718. list($key, $value) = $valArr;
  719. $itemArr[$key] = $field . ' ' . $key;
  720. }
  721. }
  722. } else {
  723. foreach ($item as $k => $v) {
  724. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  725. }
  726. }
  727. return $itemArr;
  728. }
  729. }