fusonic/api-documentation-bundle

Symfony 扩展包,用于使用 NelmioApiDocBundle 自动生成文档。

0.1.1 2024-09-16 12:25 UTC

This package is auto-updated.

Last update: 2024-09-16 12:27:41 UTC


README

License Latest Version Total Downloads php 8.2+

关于

本扩展包可以简化您(json)API路由的文档生成。它提供了一种自定义的路由注解,可以解析路由的输入和输出模型,为NelmioApiDocBundle生成文档定义。如果您为输入和输出使用了类型提示,它可以自动检测,请参阅使用方法了解如何操作。

仅使用NelmioApiDocBundle时,您可能会发现需要编写许多具有重复模式的注解。本扩展包将常见的注解组合捆绑到一个单独的路由属性中。

本扩展包可以很好地与http-kernel-bundle一起使用。

安装

使用 composer 从 Packagist 安装扩展包。

composer require fusonic/api-documentation-bundle

要求

  • PHP 8.2+
  • Symfony 5.4+

如果 Symfony 没有将扩展包添加到扩展包配置中,请添加以下内容(默认位于 config/bundles.php

<?php

return [
    // ...
    Fusonic\ApiDocumentationBundle\FusonicApiDocumentationBundle::class => ['all' => true],
];

接下来,您需要配置NelmioApiDocBundle

本扩展包有一个可选的配置

fusonic_api_documentation:
    # An attribute, class, or interface that is used to detect which object to parse the "input" model from.
    # If you do not configure this, automatic input detection will not work.
    request_object_class: Fusonic\ApiDocumentationBundle\Tests\App\FromRequest

使用方法

tests中可以找到不同的示例。

带有自动类型检测的示例路由

如果您有一些允许您直接从控制器返回对象的响应监听器,则可以使用基于返回类型或返回注解的自动输出检测。

    #[DocumentedRoute(path: '/test-return-type/{id}', methods: ['GET'])]
    public function testReturnType(#[FromRequest] TestRequest $query): TestResponse
    {
        return new TestResponse($query->id);
    }

如果您返回数组或通用类型,可以设置返回类型(例如:SomeType[] 或 `SomeGeneric`)。这里的要求是您只能有一个返回类型。不支持多个返回类型。

带有手动输入/输出的示例路由

如果您不支持参数解析和直接返回对象,您可以手动定义inputoutput类。

    #[DocumentedRoute(path: '/test-return-type/{id}', methods: ['GET'], input: TestRequest::class, output: TestResponse::class)]
    public function testReturnType(int $id): JsonResponse
    {
    return new JsonResponse(['id' => $query->id], 200);
    }

您也可以指定输出内置类型,例如string

#[DocumentedRoute(path: '/test-return-type/{id}', methods: ['GET'], input: TestRequest::class, output: 'string')]

如果您的手动定义输出是集合,除了output之外,您还可以设置outputIsCollection: true

#[DocumentedRoute(
    path: '/test-return-type/{id}',
    methods: ['GET'],
    input: TestRequest::class,
    description: 'custom description',
    statusCode: 200,
    output: 'string',
    outputIsCollection: true
)]

贡献

这是fusonic/php-extensions仓库的子树分割。请在那里创建您的 pull request。