* Date: 2023/02/05 * Time: 20:33 */ namespace app\admin\controller; use file\FileHelper; /** * 演示代码生成,只生成接口 * Class ApiGeneration * @package app\admin\controller */ class ApiGeneration extends CodeGeneration { public function generation() { $post = $this->request->post(); if ($this->request->isPost()) { $validate = new \think\Validate([ ['table', 'require|max:50', '请选择数据库表'], ]); if (!$validate->check($post)) { $this->error('提交失败:' . $validate->getError()); } } $nameAndComment = explode('|', $post['table']); $tableName = $nameAndComment[0]??''; $menuName = $nameAndComment[1] ?: $tableName; $humpName = $this->getHumpName($tableName); $underLineName = $this->getUnderLineName($tableName); $fieldsInfo = $this->getFieldsInfoByTableName($tableName); $tpData = [ 'fieldsInfo' => $fieldsInfo, 'humpName' => $humpName, 'underLineName' => $underLineName, 'menuName' => $menuName, 'tableName' => $tableName, 'crud' => $post['crud']??[], ]; //模板文件目录 $tpdir = APP_PATH . 'admin' . DS . 'view' . DS . 'code_generation' . DS . 'tpl' . DS; //生成文件路径 $ControllerPath = APP_PATH . 'api' . DS . 'controller' . DS . $humpName . '.php'; $ModelPath = APP_PATH . 'common' . DS . 'model' . DS . $humpName . '.php'; $ApiDocPath = APP_PATH . 'api' . DS . 'controller' . DS . $humpName . '.md'; if (!$this->request->has('cover')) { //检查文件是否已存在 $checkMsg = ""; if (file_exists($ControllerPath)) { $checkMsg .= str_replace(APP_PATH, '', $ControllerPath) . " 已存在" . '
'; } if (file_exists($ModelPath)) { $checkMsg .= str_replace(APP_PATH, '', $ModelPath) . " 已存在" . '
'; } if (file_exists($ApiDocPath)) { $checkMsg .= str_replace(APP_PATH, '', $ApiDocPath) . " 已存在" . '
'; } if (!empty($checkMsg)) { $checkMsg .= "确认生成并覆盖?"; $this->error($checkMsg); } } //生成controller $content = $this->fetch($tpdir . 'ApiController.php.tp', $tpData); FileHelper::save($ControllerPath, "fetch($tpdir . 'Model.php.tp', $tpData); FileHelper::save($ModelPath, "fetch($tpdir . 'ApiDoc.md.tp', $tpData); FileHelper::save($ApiDocPath, $content); $this->success("success"); } }