tp6实现自动生成swagger /components/schemas文件

一、思路

1、创建tp6命令行工具

2、读取数据库表结构

3、生成swagger schemas格式

4、保存文件到指定位置

 

二、自定义tp console

第一步,创建一个自定义命令类文件,运行指令

php think make:command Schema schema

会生成一个app\command\Schema 命令行指令类,我们修改内容如下:

<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Schema extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('schema')
            ->setDescription('the schema command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('schema');
    }
 
}

第二步,配置config/console.php文件

<?php
return [
    'commands' => [
        'hello' => 'app\command\Schema',
    ]
];

第三步,命令行运行schema命令

php think schema
可以正常输出console文件输出的内容
 
三、编写生成schema代码
<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Db;

class Schema extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('schema')
            ->setDescription('the schema command');
    }

    protected function execute(Input $input, Output $output)
    {
        $tables = Db::query("SHOW TABLE STATUS");
        foreach ($tables as $key => $table) {
            $fileds = Db::query("SHOW FULL COLUMNS FROM " . $table['Name']);
            $content = <<<END
<?php
/**
 * Class {$this->getDbName($table['Name'])}
 * 创建数据模型
 * @OA\Schema(
 *     title="{$this->getDbName($table['Name'])} model",
 *     description="{$this->getDbName($table['Name'])} model",
 * )
 */
class {$this->getDbName($table['Name'])}
{
END;
            $content .= PHP_EOL;
            foreach ($fileds as $item) {
                $content .= "\t/**" . PHP_EOL;
                $content .= "\t* ------" . PHP_EOL;
                $content .= "\t* @OA\Property(format=\"{$this->getFormat($item['Type'])}\",title=\"{$item['Comment']}\",default=\"{$item['Default']}\")" . PHP_EOL;
                $content .= "\t* @var {$this->getType($item['Type'])}" . PHP_EOL;
                $content .= "\t*/" . PHP_EOL;
                $content .= "\tprivate \${$item["Field"]};" . PHP_EOL;
                $content .= PHP_EOL;
            }
            $content .= "}";
            file_put_contents(root_path() . "app/common/schema/" . $this->getDbName($table['Name']) . ".php", $content);
        }
        // 指令输出
        $output->writeln('schema');
    }

    private function getType($value)
    {
        $type = "string";
        if (strpos($value, "int") !== false) {
            $type = "integer";
        } elseif (strpos($value, "float") !== false || strpos($value, "double") !== false || strpos($value, "decimal") !== false) {
            $type = "number";
        }
        return $type;
    }

    private function getFormat($value)
    {
        $format = "string";
        if (strpos($value, "int") !== false) {
            $format = "int64";
        } elseif (strpos($value, "float") !== false || strpos($value, "double") !== false || strpos($value, "decimal") !== false) {
            $format = "float";
        } elseif (strpos($value, "date") !== false) {
            $format = "date";
        } elseif (strpos($value, "datetime") !== false || strpos($value, "timestamp") !== false) {
            $format = "date-time	";
        }
        return $format;
    }

    private function getDbName($dbname)
    {
        $prefix = Config::get("database.connections.mysql.prefix");
        $dbname = str_replace($prefix, "", $dbname);
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $dbname)));
    }
}

到此为止代码部分已全部完成。

 

四、参考资料

 

 

 

 

 

 

五、swagger生成文件使用

controller文件

<?php
declare (strict_types=1);

namespace app\restapi\controller;

use app\common\controller\BaseController;
use app\common\utils\Res;
use app\user\model\UserSign;
use think\Request;

class User extends BaseController
{

    /**
     * @OA\Get  (path="/restapi/user/signList",
     *   tags={"用户管理"},
     *   summary="签到列表",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="user_id", in="query", description="user_id", @OA\Schema(type="int", default="")),
     *   @OA\Response(
     *      response="200",
     *      description="成功状态",
     *      @OA\JsonContent(
     *            type="array",
     *            @OA\Items(ref="#/components/schemas/UserSign")
     *      )
     *   )
     * )
     */
    public function signList(Request $request)
    {
        $list = UserSign::weekList($request);
        return Res::ok($list);
    }

    /**
     * @OA\Post (path="/restapi/user/signCreate",
     *   tags={"用户管理"},
     *   summary="用户签到",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\RequestBody(
     *       @OA\MediaType(
     *           mediaType="application/x-www-form-urlencoded",
     *           @OA\Schema(
     *              type="object",
     *              @OA\Property(
     *                 property="user_id",
     *                 description="user_id",
     *                 type="int",
     *              ),
     *           )
     *       )
     *   ),
     *   @OA\Response(
     *      response="200",
     *      description="成功状态",
     *      @OA\JsonContent(
     *            type="array",
     *            @OA\Items(ref="#/components/schemas/UserSign")
     *      )
     *   )
     * )
     */
    public function signCreate(Request $request)
    {
        $list = UserSign::createSave($request);
        if ($list === true) {
            return Res::ok($list);

        }
        return Res::error($list);
    }

}

 

schema文件

<?php
/**
 * Class UserSign
 * 创建数据模型
 * @OA\Schema(
 *     title="UserSign model",
 *     description="UserSign model",
 * )
 */
class UserSign
{
	/**
	* ------
	* @OA\Property(format="int64",title="签到id",default="")
	* @var integer
	*/
	private $sign_id;

	/**
	* ------
	* @OA\Property(format="int64",title="会员id",default="")
	* @var integer
	*/
	private $user_id;

	/**
	* ------
	* @OA\Property(format="string",title="交易号",default="")
	* @var string
	*/
	private $transaction_id;

	/**
	* ------
	* @OA\Property(format="int64",title="积分",default="")
	* @var integer
	*/
	private $grade;

	/**
	* ------
	* @OA\Property(format="int64",title="连续签到记录数",default="")
	* @var integer
	*/
	private $succ_record;

	/**
	* ------
	* @OA\Property(format="int64",title="创建时间",default="")
	* @var integer
	*/
	private $created_at;

}

  

posted @ 2022-04-13 10:14  北漂生活  阅读(721)  评论(0编辑  收藏  举报