PHP code example of cvcv / think-openapi

1. Go to this page and download the library: Download cvcv/think-openapi library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cvcv / think-openapi example snippets




namespace app\controller;

use app\validate\UserValidate;
use app\resource\UserResource;
use Cvcv\ThinkOpenApi\Attribute\ApiDoc;
use Cvcv\ThinkOpenApi\Attribute\ApiGroup;
use Cvcv\ThinkOpenApi\OpenApi\ResponseDataType;
use think\response\Json;

#[ApiGroup(tags: ['Users'])]
final class UserController
{
    #[ApiDoc(
        summary: '用户列表',
        validate: UserValidate::class,
        scene: 'index',
        response: UserResource::class,
        responseType: ResponseDataType::Page,
    )]
    public function index(): Json
    {
        return json();
    }

    #[ApiDoc(
        summary: '创建用户',
        tags: ['Write'],
        validate: UserValidate::class,
        scene: 'store',
        response: UserResource::class,
    )]
    public function save(): Json
    {
        return json();
    }

    #[ApiDoc(
        summary: '删除用户',
    )]
    public function delete(): \think\Response
    {
        return response('', 204);
    }
}



use app\controller\UserController;
use think\facade\Route;

Route::get('users', [UserController::class, 'index']);
Route::post('users', [UserController::class, 'save']);
Route::delete('users/<id>', [UserController::class, 'delete']);

#[ApiDoc(
    summary: '用户列表',
    response: UserResource::class,
    extensions: [
        'x-code-samples' => [
            [
                'lang' => 'curl',
                'source' => 'curl /users',
            ],
        ],
    ],
)]
public function index(): Json
{
    return json();
}

use Cvcv\ThinkOpenApi\Attribute\ApiParam;

#[ApiParam(
    name: 'page[number]',
    in: 'query',
    description: '页码',
    schema: ['type' => 'integer', 'minimum' => 1],
    example: 1,
)]
#[ApiParam(
    name: 'X-Request-ID',
    in: 'header',
    description: '请求 ID',
    schema: ['type' => 'string'],
)]
public function index(): Json
{
    return json();
}

use Cvcv\ThinkOpenApi\Attribute\ApiResponse;

#[ApiResponse(
    status: 400,
    description: '验证失败',
    content: [
        'application/json' => [
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'message' => ['type' => 'string'],
                ],
            ],
        ],
    ],
)]
public function save(): Json
{
    return json();
}



namespace app\validate;

use app\enum\UserStatus;
use think\Validate;

final class UserValidate extends Validate
{
    protected $rule = [
        'filter.name' => 'string|max:255',
        'page.number' => 'integer|between:1,100000',
        'profile.name' => '
        'status_list.*' => 'string|enum:' . UserStatus::class,
        'members' => '��启用',
        'tags' => '标签列表',
        'tags.*' => '标签',
        'status_list' => '状态列表',
        'status_list.*' => '状态项',
        'members' => '成员列表',
        'members.*.id' => '成员 ID',
        'members.*.name' => '成员名称',
    ];

    protected $scene = [
        'index' => ['filter.name', 'page.number'],
        'store' => [
            'profile.name',
            'profile.email',
            'status',
            'enabled',
            'tags',
            'tags.*',
            'status_list',
            'status_list.*',
            'members',
            'members.*.id',
            'members.*.name',
        ],
    ];
}

protected $rule = [
    'ids' => 'ags' => 'tus_list' => 's,

    'members' => 'ng|max:32',
];



namespace app\resource;

use Cvcv\ThinkOpenApi\OpenApi\ObjectSchema;
use Cvcv\ThinkOpenApi\OpenApi\Schema;
use Cvcv\ThinkOpenApi\OpenApi\SchemaProvider;

final class UserResource implements SchemaProvider
{
    public static function openApiSchemaName(): string
    {
        return 'User';
    }

    public static function openApiSchemas(): array
    {
        return ObjectSchema::make(self::openApiSchemaName())
            ->property('id', Schema::integer('用户 ID'), 

Schema::example(Schema::string('用户名称'), 'Alice');
Schema::deprecated(Schema::string('旧字段'));
Schema::with(Schema::string(), ['x-displayName' => '状态']);

use Cvcv\ThinkOpenApi\OpenApi\Response\RawDataSchemaFactory;

return [
    'response_schema_factory' => RawDataSchemaFactory::class,
];

return [
    'security' => [
        'bearer' => [
            'middleware' => app\middleware\AuthToken::class,
            'scheme_name' => 'bearerAuth',
            'description' => 'Bearer Token 认证。',
        ],
    ],
];



namespace app\openapi;

use Cvcv\ThinkOpenApi\OpenApi\Security\AuthState;
use Cvcv\ThinkOpenApi\OpenApi\Security\MiddlewareSecurityInspector;

final class AdminSecurityInspector implements MiddlewareSecurityInspector
{
    public function inspect(string $middleware, array $parameters, AuthState $state): void
    {
        if ($middleware !== \app\middleware\AdminAuth::class) {
            return;
        }

        $state->

return [
    'security' => [
        'inspectors' => [
            \Cvcv\ThinkOpenApi\OpenApi\Security\BearerMiddlewareSecurityInspector::class,
            \app\openapi\AdminSecurityInspector::class,
        ],
    ],
];

return [
    'title' => 'ThinkPHP OpenAPI',
    'version' => '0.1.0',
    'servers' => [
        ['url' => '/'],
    ],
    'json_url' => '/docs/api.json',
    'spec_path' => 'runtime/docs/openapi.json',
    'production_envs' => ['prod', 'production'],
    'regenerate_on_request' => false,
    'routes' => [
        'enabled' => true,
        'scalar' => 'docs/api',
        'stoplight' => 'docs/api/stoplight',
        'json' => 'docs/api.json',
    ],
    'ui' => [
        'scalar' => [
            'script_url' => 'https://cdn.jsdelivr.net/npm/@scalar/api-reference',
        ],
        'stoplight' => [
            'script_url' => 'https://unpkg.com/@stoplight/elements/web-components.min.js',
            'styles_url' => 'https://unpkg.com/@stoplight/elements/styles.min.css',
        ],
    ],
];

return [
    'ui' => [
        'scalar' => [
            'script_url' => '/assets/openapi/scalar.js',
        ],
        'stoplight' => [
            'script_url' => '/assets/openapi/stoplight-elements.js',
            'styles_url' => '/assets/openapi/stoplight-elements.css',
        ],
    ],
];
bash
php think docs:generate
bash
php think docs:generate
bash
php think docs:generate --output=runtime/docs/openapi.json
bash
php think docs:lint