ApiGeneration.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2023/02/05
  6. * Time: 20:33
  7. */
  8. namespace app\admin\controller;
  9. use file\FileHelper;
  10. /**
  11. * 演示代码生成,只生成接口
  12. * Class ApiGeneration
  13. * @package app\admin\controller
  14. */
  15. class ApiGeneration extends CodeGeneration
  16. {
  17. public function generation()
  18. {
  19. $post = $this->request->post();
  20. if ($this->request->isPost()) {
  21. $validate = new \think\Validate([
  22. ['table', 'require|max:50', '请选择数据库表'],
  23. ]);
  24. if (!$validate->check($post)) {
  25. $this->error('提交失败:' . $validate->getError());
  26. }
  27. }
  28. $nameAndComment = explode('|', $post['table']);
  29. $tableName = $nameAndComment[0]??'';
  30. $menuName = $nameAndComment[1] ?: $tableName;
  31. $humpName = $this->getHumpName($tableName);
  32. $underLineName = $this->getUnderLineName($tableName);
  33. $fieldsInfo = $this->getFieldsInfoByTableName($tableName);
  34. $tpData = [
  35. 'fieldsInfo' => $fieldsInfo,
  36. 'humpName' => $humpName,
  37. 'underLineName' => $underLineName,
  38. 'menuName' => $menuName,
  39. 'tableName' => $tableName,
  40. 'crud' => $post['crud']??[],
  41. ];
  42. //模板文件目录
  43. $tpdir = APP_PATH . 'admin' . DS . 'view' . DS . 'code_generation' . DS . 'tpl' . DS;
  44. //生成文件路径
  45. $ControllerPath = APP_PATH . 'api' . DS . 'controller' . DS . $humpName . '.php';
  46. $ModelPath = APP_PATH . 'common' . DS . 'model' . DS . $humpName . '.php';
  47. $ApiDocPath = APP_PATH . 'api' . DS . 'controller' . DS . $humpName . '.md';
  48. if (!$this->request->has('cover')) {
  49. //检查文件是否已存在
  50. $checkMsg = "";
  51. if (file_exists($ControllerPath)) {
  52. $checkMsg .= str_replace(APP_PATH, '', $ControllerPath) . " 已存在" . '</br>';
  53. }
  54. if (file_exists($ModelPath)) {
  55. $checkMsg .= str_replace(APP_PATH, '', $ModelPath) . " 已存在" . '</br>';
  56. }
  57. if (file_exists($ApiDocPath)) {
  58. $checkMsg .= str_replace(APP_PATH, '', $ApiDocPath) . " 已存在" . '</br>';
  59. }
  60. if (!empty($checkMsg)) {
  61. $checkMsg .= "<span style='color:red;'>确认生成并覆盖?</span>";
  62. $this->error($checkMsg);
  63. }
  64. }
  65. //生成controller
  66. $content = $this->fetch($tpdir . 'ApiController.php.tp', $tpData);
  67. FileHelper::save($ControllerPath, "<?php" . PHP_EOL . $content);
  68. //生成model
  69. $content = $this->fetch($tpdir . 'Model.php.tp', $tpData);
  70. FileHelper::save($ModelPath, "<?php" . PHP_EOL . $content);
  71. //生成api doc
  72. $content = $this->fetch($tpdir . 'ApiDoc.md.tp', $tpData);
  73. FileHelper::save($ApiDocPath, $content);
  74. $this->success("success");
  75. }
  76. }