MakeAdmin.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. /**
  36. * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表
  37. */
  38. protected $enumRadioSuffix = ['state', 'status'];
  39. /**
  40. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  41. */
  42. protected $intDateSuffix = ['time'];
  43. /**
  44. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  45. */
  46. protected $intListSuffix = ['images', 'ids', 'list'];
  47. /**
  48. * 开关后缀
  49. */
  50. protected $switchSuffix = ['switch'];
  51. protected function configure()
  52. {
  53. parent::configure();
  54. $this->setName('make')
  55. ->addOption('table', 't', Option::VALUE_REQUIRED, 'The name of the table to create')
  56. ->addOption('path', 'p', Option::VALUE_OPTIONAL, 'path', null)
  57. ->addOption('hidden', 'x', Option::VALUE_OPTIONAL, 'hidden fields', null)
  58. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force replace file', null)
  59. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files', null)
  60. ->setDescription('Create a new table class');
  61. }
  62. public function execute(Input $input, Output $output)
  63. {
  64. $table = $input->getOption('table') ?: '';
  65. if (!$table) {
  66. throw new Exception('Please enter the table name');
  67. }
  68. //自定义控制器
  69. $path = $input->getOption('path');
  70. $force = $input->getOption('force');
  71. $hidden = $input->getOption('hidden');
  72. $delete = $input->getOption('delete');
  73. $hidden = str_replace(',', ',', $hidden);
  74. $hidden = explode(',', $hidden);
  75. array_push($hidden, $this->deleteTimeField);
  76. $connect = Db::connect('mysql');
  77. $dbname = Config::get('database.connections.mysql.database');
  78. $prefix = Config::get('database.connections.mysql.prefix');
  79. //检查主表
  80. $modelName = $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
  81. $modelTableType = 'table';
  82. $modelTableTypeName = $modelTableName = $modelName;
  83. $modelTableInfo = $connect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  84. if (!$modelTableInfo) {
  85. $modelTableType = 'name';
  86. $modelTableName = $prefix . $modelName;
  87. $modelTableInfo = $connect->query("SHOW TABLE STATUS LIKE '{$modelTableName}'", [], true);
  88. if (!$modelTableInfo) {
  89. throw new Exception("table not found");
  90. }
  91. }
  92. $modelTableInfo = $modelTableInfo[0];
  93. //模型
  94. list($modelNamespace, $modelName, $modelFile, $modelArr) = $this->getModelData($path, $table);
  95. list($serviceNamespace, $serviceName, $serviceFile, $serviceArr) = $this->getServicesData($path, $table);
  96. list($controllerNamespace, $controllerName, $controllerFile, $controllerArr, $controllerPath, $resourceName) = $this->getControllerData($path, $table);
  97. list($validateNamespace, $validateName, $validateFile, $validateArr) = $this->getValidateData($path, $table);
  98. if ($delete) {
  99. $readyFiles = [$controllerFile, $modelFile, $validateFile, $serviceFile];
  100. foreach ($readyFiles as $k => $v) {
  101. $output->warning($v);
  102. }
  103. if (!$force) {
  104. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  105. $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
  106. if (trim($line) != 'yes') {
  107. throw new Exception("Operation is aborted!");
  108. }
  109. }
  110. foreach ($readyFiles as $k => $v) {
  111. if (file_exists($v)) {
  112. unlink($v);
  113. }
  114. //删除空文件夹
  115. switch ($v) {
  116. case $modelFile:
  117. $this->removeEmptyBaseDir($v, $modelArr);
  118. break;
  119. case $validateFile:
  120. $this->removeEmptyBaseDir($v, $validateArr);
  121. break;
  122. case $serviceArr:
  123. $this->removeEmptyBaseDir($v, $serviceArr);
  124. break;
  125. default:
  126. $this->removeEmptyBaseDir($v, $controllerArr);
  127. }
  128. }
  129. $output->info("Delete Successed");
  130. return;
  131. }
  132. //非覆盖模式时如果存在控制器文件则报错
  133. if (is_file($controllerFile) && !$force) {
  134. throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  135. }
  136. //非覆盖模式时如果存在模型文件则报错
  137. if (is_file($modelFile) && !$force) {
  138. throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  139. }
  140. //非覆盖模式时如果存在验证文件则报错
  141. if (is_file($serviceFile) && !$force) {
  142. throw new Exception("services already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  143. }
  144. //非覆盖模式时如果存在验证文件则报错
  145. if (is_file($validateFile) && !$force) {
  146. throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  147. }
  148. //从数据库中获取表字段信息
  149. $sql = "SELECT * FROM `information_schema`.`columns` "
  150. . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  151. . "ORDER BY ORDINAL_POSITION";
  152. //加载主表的列
  153. $columnList = $connect->query($sql, [$dbname, $modelTableName]);
  154. $fieldArr = [];
  155. $priKeyArr = [];
  156. foreach ($columnList as $k => $v) {
  157. $fieldArr[] = $v['COLUMN_NAME'];
  158. if ($v['COLUMN_KEY'] == 'PRI') {
  159. $priKeyArr[] = $v['COLUMN_NAME'];
  160. }
  161. }
  162. if (!$priKeyArr) {
  163. throw new Exception('Primary key not found!');
  164. }
  165. if (count($priKeyArr) > 1) {
  166. throw new Exception('Multiple primary key not support!');
  167. }
  168. $priKey = reset($priKeyArr);
  169. try {
  170. $setAttrArr = [];
  171. $getAttrArr = [];
  172. $getEnumArr = [];
  173. $hiddenArr = [];
  174. $appendAttrList = [];
  175. $exportAttr = [];
  176. $validateRules = [];
  177. $searchAttr = [];
  178. $searchFieldAttr = [];
  179. $validateMessage = [];
  180. $createParams = [];
  181. //循环所有字段,开始构造视图的HTML和JS信息
  182. foreach ($columnList as $k => $v) {
  183. $field = $v['COLUMN_NAME'];
  184. $itemArr = [];
  185. // 这里构建Enum和Set类型的列表数据
  186. if (in_array($v['DATA_TYPE'], ['enum', 'set', 'tinyint'])) {
  187. if ($v['DATA_TYPE'] !== 'tinyint') {
  188. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  189. $itemArr = explode(',', str_replace("'", '', $itemArr));
  190. }
  191. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  192. //如果类型为tinyint且有使用备注数据
  193. if ($itemArr && !in_array($v['DATA_TYPE'], ['enum', 'set'])) {
  194. $v['DATA_TYPE'] = 'enum';
  195. }
  196. }
  197. // 语言列表
  198. $langList = [];
  199. if ($v['COLUMN_COMMENT'] != '') {
  200. $langList = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  201. }
  202. if (in_array($field, $hidden)) {
  203. $this->hiddenAttr($hiddenArr, $field);
  204. }
  205. if ($v['COLUMN_KEY'] == 'PRI')
  206. $exportAttr[$field] = $langList[$field] ?? parseName($field, 1);
  207. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $hidden)) {
  208. if ($field == $this->addTimeField) {
  209. if ($v['DATA_TYPE'] == 'int') {
  210. $this->getAttr($getAttrArr, $field, 'add_time');
  211. } else {
  212. $this->getAttr($getAttrArr, $field, 'add_time_datetime');
  213. }
  214. $this->searchAttr($searchFieldAttr, 'time');
  215. $exportAttr[$field] = $langList[$field] ?? '添加时间';
  216. } else {
  217. $inputType = $this->getFieldType($v);
  218. // 如果默认值非null,则是一个必选项
  219. if ($inputType == 'select') {
  220. $this->getEnum($getEnumArr, $field, $itemArr, $langList);
  221. //添加一个获取器
  222. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  223. if ($v['DATA_TYPE'] == 'set') {
  224. $this->setAttr($setAttrArr, $field, $inputType);
  225. }
  226. $this->setCreate($createParams, $v);
  227. $this->appendAttr($appendAttrList, $field);
  228. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  229. } else if ($inputType == 'list') {
  230. $this->getAttr($getAttrArr, $field, $inputType);
  231. $this->setAttr($setAttrArr, $field, $inputType);
  232. $this->setCreate($createParams, $v);
  233. $this->appendAttr($appendAttrList, $field);
  234. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  235. } elseif ($inputType == 'datetime') {
  236. $this->getAttr($getAttrArr, $field, $inputType);
  237. $this->setAttr($setAttrArr, $field, $inputType);
  238. $this->setCreate($createParams, $v);
  239. $this->appendAttr($appendAttrList, $field);
  240. $exportAttr[$field . '_chs'] = $langList[$field] ?? parseName($field, 1);
  241. } else {
  242. $this->setCreate($createParams, $v);
  243. $exportAttr[$field] = $langList[$field] ?? parseName($field, 1);
  244. }
  245. $this->checkValidate($validateRules, $validateMessage, $v, $field, $langList[$field] ?? parseName($field, 1), $itemArr);
  246. $this->searchAttrHandel($searchAttr, $searchFieldAttr, $field, $langList[$field] ?? parseName($field, 1), $inputType);
  247. }
  248. }
  249. }
  250. //表注释
  251. $tableComment = $modelTableInfo ? $modelTableInfo['Comment'] : '';
  252. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) : $tableComment;
  253. $data = [
  254. 'table' => $table,
  255. 'tableComment' => $tableComment,
  256. 'tableName' => $modelTableName,
  257. 'resourceName' => $resourceName,
  258. 'path' => $controllerPath,
  259. 'pk' => $priKey,
  260. 'controllerNamespace' => $controllerNamespace,
  261. 'controllerName' => $controllerName,
  262. 'modelNamespace' => $modelNamespace,
  263. 'modelName' => $modelName,
  264. 'validateNamespace' => $validateNamespace,
  265. 'validateName' => $validateName,
  266. 'servicesNamespace' => $serviceNamespace,
  267. 'servicesName' => $serviceName,
  268. 'modelTableName' => $modelTableName,
  269. 'modelTableType' => $modelTableType,
  270. 'modelTableTypeName' => $modelTableTypeName,
  271. 'softDeleteClassPath' => in_array($this->deleteTimeField, $fieldArr) ? "use think\model\concern\SoftDelete;" : '',
  272. 'softDelete' => in_array($this->deleteTimeField, $fieldArr) ? "use SoftDelete;" : '',
  273. 'hiddenArrList' => implode(",\n\t", $hiddenArr),
  274. 'appendAttrList' => implode(",\n\t", $appendAttrList),
  275. 'getEnumList' => implode("\n\n", $getEnumArr),
  276. 'getAttrList' => implode("\n\n", $getAttrArr),
  277. 'setAttrList' => implode("\n\n", $setAttrArr),
  278. 'validateRules' => implode(",\n", $this->handelArrayDate($validateRules)),
  279. 'validateMessage' => implode(",\n", $this->handelArrayDate($validateMessage)),
  280. 'exportAttrList' => implode(",\n", $this->handelArrayDate($exportAttr)),
  281. 'createParams' => implode(",\n\t", $createParams),
  282. 'searchFieldAttr' => implode(",\n\t", $searchFieldAttr),
  283. 'searchAttrList' => implode("\n\n", $searchAttr),
  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->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum') {
  617. $inputType = "select";
  618. }
  619. // 指定后缀结尾且类型为enum,说明是个单选框
  620. if ($this->isMatchSuffix($fieldsName, $this->intListSuffix)) {
  621. $inputType = "list";
  622. }
  623. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  624. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null) {
  625. $inputType = "select";
  626. }
  627. return $inputType;
  628. }
  629. /**
  630. * 判断是否符合指定后缀
  631. * @param string $field 字段名称
  632. * @param mixed $suffixArr 后缀
  633. * @return boolean
  634. */
  635. protected function isMatchSuffix($field, $suffixArr)
  636. {
  637. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  638. foreach ($suffixArr as $k => $v) {
  639. if (preg_match("/{$v}$/i", $field)) {
  640. return true;
  641. }
  642. }
  643. return false;
  644. }
  645. /**
  646. * 获取模型相关信息
  647. * @param $module
  648. * @param $model
  649. * @param $table
  650. * @return array
  651. */
  652. protected function getModelData($path, $table)
  653. {
  654. return $this->getParseNameData($path, $table, 'model');
  655. }
  656. /**
  657. * 获取模型相关信息
  658. * @param $module
  659. * @param $model
  660. * @param $table
  661. * @return array
  662. */
  663. protected function getServicesData($path, $table)
  664. {
  665. return $this->getParseNameData($path, $table, 'services');
  666. }
  667. /**
  668. * 获取模型相关信息
  669. * @param $module
  670. * @param $model
  671. * @param $table
  672. * @return array
  673. */
  674. protected function getValidateData($path, $table)
  675. {
  676. return $this->getParseNameData($path, $table, 'validate');
  677. }
  678. protected function getControllerData($path, $table)
  679. {
  680. return $this->getParseNameData($path, $table, 'controller');
  681. }
  682. /**
  683. * 获取已解析相关信息
  684. * @param string $name 自定义名称
  685. * @param string $table 数据表名
  686. * @param string $type 解析类型,本例中为controller、model、validate
  687. * @return array
  688. */
  689. protected function getParseNameData($path, $table, $type)
  690. {
  691. $parseName = parseName($table, 1);
  692. $parseName = $parseName . $this->after[$type];
  693. if (!$path) {
  694. $path = str_replace('_', '/', $table);
  695. $path = str_replace(['.', '/', '\\'], '/', $path);
  696. $arr = explode('/', $path);
  697. array_pop($arr);
  698. } else {
  699. $path = str_replace(['.', '/', '\\'], '/', $path);
  700. $arr = explode('/', $path);
  701. }
  702. $resourceName = $table;
  703. foreach ($arr as $v) {
  704. if (strpos($resourceName, $v . '_') === 0) {
  705. $resourceName = substr($resourceName, strlen($v . '_'));
  706. }
  707. }
  708. $parseArr = $arr;
  709. array_push($parseArr, $parseName);
  710. $appNamespace = Config::get('app.app_namespace');
  711. $parseNamespace = "{$appNamespace}\\{$type}" . (in_array($type, ['controller', 'validate']) ? '\\admin' : '') . ($arr ? "\\" . implode("\\", $arr) : "");
  712. $moduleDir = $this->app->getRootPath() . 'app' . DS . $type . DS . ((in_array($type, ['controller', 'validate']) ? 'admin' : '') . DS);
  713. $parseFile = $moduleDir . ($arr ? implode(DS, $arr) . DS : '') . $parseName . '.php';
  714. return [$parseNamespace, $parseName, $parseFile, $parseArr, ($arr ? implode('.', $arr) . '.' : ''), $resourceName];
  715. }
  716. protected function getItemArray($item, $field, $comment)
  717. {
  718. $itemArr = [];
  719. $comment = str_replace(',', ',', $comment);
  720. if (stripos($comment, ':') !== false && stripos($comment, '=') !== false) {
  721. list($fieldLang, $item) = explode(':', $comment);
  722. $itemArr = [];
  723. foreach (explode(',', $item) as $k => $v) {
  724. $valArr = explode('=', $v);
  725. if (count($valArr) == 2) {
  726. list($key, $value) = $valArr;
  727. $itemArr[$key] = $field . ' ' . $key;
  728. }
  729. }
  730. } else {
  731. foreach ($item as $k => $v) {
  732. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  733. }
  734. }
  735. return $itemArr;
  736. }
  737. }