bornfight/jsonapi-documentation

此组件允许自动生成 JsonApi 文档

v0.1.2 2020-09-21 14:30 UTC

This package is auto-updated.

Last update: 2024-09-21 23:24:54 UTC


README

这是一个用于与 Pakhanad JsonApi Bundle 结合使用的 Symfony 5 包。它可以在开发过程中任何时候生成 API 文档,而不仅仅是生成实体之后。这在开发过程中需要大量更改域模型时特别有用。

安装

要安装此包,请使用 composer

composer require bornfight/jsonapi-documentation --dev

通过添加以下内容注册您的包到 bundles.php

    Bornfight\JsonApiDocumentation\BornfightJsonApiDocumentation::class => [ 'all' => true],

用法

要生成 JsonApi 文档,使用以下命令

php bin/console jsonapi:documentation:generate

这将创建 documentation/api.yaml 文件,可以用于在像 Swagger 这样的外部服务上作为 API 文档,或者用于生成 Postman 请求。

您可以在任何时候使用此命令,它将查找 API 中的最新更改并覆盖旧的 api.yaml 文件。

工作原理

此命令将检查您的控制器类并查找以下方法

  • list()
  • new()
  • view()
  • edit()
  • delete()

之后,它将检查您的 Transformer 和 Hydrator 类以生成请求和响应模式。它期望以下方法

getRelationships()
getAttributes()

这些方法应该返回一个数组。数组元素的键将被用作请求中的属性和关系。

自定义

使用不同的模板

如果您想使用不同的模板,可以在 documentoion/ 目录中创建 template.yaml 文件。原始模板文件

#template.yaml
openapi: 3.0.0
info:
  description: "This is where you can give more detailed description of your API"
  version: "1.0.0"
  title: "Openapi JsonApi"
  termsOfService: "https://swagger.org.cn/terms/"
  license:
    name: "Apache 2.0"
    url: "https://apache.ac.cn/licenses/LICENSE-2.0.html"
paths:
externalDocs:
  description: "Find out more about Swagger"
  url: "https://swagger.org.cn"
servers:
  - url: https://:8000/api
    description: Local Environment
components:
  securitySchemes:
    bearerToken:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerToken: []

添加自定义文档

如果您想添加自定义路由,可以创建一个实现 CustomDocumentationInterface 类的类。您还需要为该类添加一个带有以下标记的标签:

#services.yaml
    App\Documentation\CustomDocumentationHandler:
        tags: ['doc.custom_handler']

之后,您可以在生成过程之后添加任何所需的逻辑,例如

<?php

namespace App\Documentation;

use Bornfight\JsonApiDocumentation\Documentation\CustomDocumentationInterface;
use Symfony\Component\Yaml\Yaml;

class CustomDocumentationHandler implements CustomDocumentationInterface
{
    /**
     * @var string
     */
    private $projectDir;

    public function __construct(string $projectDir)
    {
        $this->projectDir = $projectDir;
    }


    public function decorate(array &$documentation): void
    {
        $baseDir = '/documentation/parts/';

        // add custom routes
        //login
        $templateFile = $this->projectDir . $baseDir . 'login.yaml';
        $routeDefinition = Yaml::parseFile($templateFile);
        $documentation['paths']['/auth/login'] = $routeDefinition;
    }
}

此代码将查找您的自定义 yaml 文件并将其内容插入到文档中。