cebe/php-openapi

读取和写入 OpenAPI yaml/json 文件,并将内容以 PHP 对象的形式访问。

1.7.0 2022-04-20 14:46 UTC

README

读取和写入 OpenAPI 3.0.x YAML 和 JSON 文件,并将内容以 PHP 对象的形式访问。

它还提供了一个 CLI 工具,用于验证和转换 OpenAPI 3.0.x 描述文件。

Latest Stable Version Total Downloads Build Status

安装

composer require cebe/php-openapi

要求

  • PHP 7.1 或更高版本(与 PHP 8 兼容良好)

使用

此库提供了读取和写入 OpenAPI 文件的低级 API。它被用于高级工具以完成出色的工作

用法

CLI 工具

$ vendor/bin/php-openapi help
PHP OpenAPI 3 tool
------------------
by Carsten Brandt <[email protected]>

Usage:
  php-openapi <command> [<options>] [input.yml|input.json] [output.yml|output.json]

  The following commands are available:

    validate   Validate the API Description in the specified input file against the OpenAPI v3.0 schema.
               Note: the validation is performed in two steps. The results are composed of
                (1) structural errors found while reading the API Description file, and
                (2) violations of the OpenAPI v3.0 schema.

               If no input file is specified input will be read from STDIN.
               The tool will try to auto-detect the content type of the input, but may fail
               to do so. You may specify --read-yaml or --read-json to force the file type.

               Exits with code 2 on validation errors, 1 on other errors and 0 on success.

    convert    Convert a JSON or YAML input file to JSON or YAML output file.

               If no input file is specified input will be read from STDIN.
               If no output file is specified output will be written to STDOUT.
               The tool will try to auto-detect the content type of the input and output file, but may fail
               to do so. You may specify --read-yaml or --read-json to force the input file type.
               and --write-yaml or --write-json to force the output file type.

               By default all references are resolved (replaced with the object referred to). You can control
               handling of references with the following arguments:

               --resolve-none      Do not resolve references.
               --resolve-external  Only resolve references that point to external files.
                                   This process is often referred to as "inlining".
               --resolve-all       Resolve all references (default).
                                   Recursive pointers will stay references.

    inline     Convert a JSON or YAML input file to JSON or YAML output file and
               resolve all external references. The output will be a single API Description file.
               This is a shortcut for calling convert --resolve-external.

    help       Shows this usage information.

  Options:

    --read-json   force reading input as JSON. Auto-detect if not specified.
    --read-yaml   force reading input as YAML. Auto-detect if not specified.
    --write-json  force writing output as JSON. Auto-detect if not specified.
    --write-yaml  force writing output as YAML. Auto-detect if not specified.
    -s, --silent  silent mode. Will hide all success/information messages and only print errors.

读取 API 描述文件

从 JSON 文件读取 OpenAPI 描述

use cebe\openapi\Reader;

// realpath is needed for resolving references with relative Paths or URLs
$openapi = Reader::readFromJsonFile(realpath('openapi.json'));

从 YAML 读取 OpenAPI 描述

use cebe\openapi\Reader;

// realpath is needed for resolving references with relative Paths or URLs
$openapi = Reader::readFromYamlFile(realpath('openapi.yaml'));
// you may also specify the URL to your API Description file
$openapi = Reader::readFromYamlFile('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml');

访问 API 描述数据

echo $openapi->openapi; // openAPI version, e.g. 3.0.0
echo $openapi->info->title; // API title
foreach($openapi->paths as $path => $definition) {
    // iterate path definitions
}

对象属性与 OpenAPI 规范 中的完全相同。您还可以访问由 规范扩展 添加的附加属性。

写入 API 描述文件

use cebe\openapi\spec\OpenApi;
use cebe\openapi\spec\PathItem;

// create base API Description
$openapi = new OpenApi([
    'openapi' => '3.0.2',
    'info' => [
        'title' => 'Test API',
        'version' => '1.0.0',
    ],
    'paths' => [],
]);
// manipulate description as needed
$openapi->paths['/test'] = new PathItem([
    'description' => 'something'
]);
// ...

$json = \cebe\openapi\Writer::writeToJson($openapi);

结果如下 JSON 数据

{
    "openapi": "3.0.0",
    "info": {
        "title": "Test API",
        "version": "1.0.0"
    },
    "paths": {
        "/test": {
            "description": "something"
        }
    }
}

使用准备好的对象写入 API 描述文件

自 1.2.0 版本以来,上述示例也可以这样编写(通过传递对象而不是数组)

use cebe\openapi\spec\OpenApi;
use cebe\openapi\spec\PathItem;
use cebe\openapi\spec\Info;


// create base API Description
$openapi = new OpenApi([
    'openapi' => '3.0.2',
    'info' => new Info([
        'title' => 'Test API',
        'version' => '1.0.0',
    ]),
    'paths' => [
        '/test' => new PathItem([
            'description' => 'something'
        ]),
    ],
]);
$json = \cebe\openapi\Writer::writeToJson($openapi);

读取 API 描述文件并解决引用

在上面的例子中,我们已经将原始 JSON 或 YAML 数据传递给了 Reader。为了能够解决对外部文件中结构的引用,我们必须提供完整的上下文。

use cebe\openapi\Reader;
use cebe\openapi\spec\OpenAPI;
use cebe\openapi\ReferenceContext;

// there are two different modes for resolving references:
// ALL: resolve all references, which will result in a large description with a lot of repetition
// but no references (except if there are recursive references, these will stop at some level)
$mode = ReferenceContext::RESOLVE_MODE_ALL;
// INLINE: only references to external files are resolved, references to places in the current file
// are still Reference objects.
$mode = ReferenceContext::RESOLVE_MODE_INLINE;

// an absolute URL or file path is needed to allow resolving external references
$openapi = Reader::readFromJsonFile('https://www.example.com/api/openapi.json', OpenAPI::class, $mode);
$openapi = Reader::readFromYamlFile('https://www.example.com/api/openapi.yaml', OpenAPI::class, $mode);

如果数据已经以不同的方式加载,您可以通过提供上下文手动解决引用,如下所示

$openapi->resolveReferences(
    new \cebe\openapi\ReferenceContext($openapi, 'https://www.example.com/api/openapi.yaml')
);

验证

该库提供简单的验证操作,检查基本的 OpenAPI 规范要求。这与 CLI 工具中“读取 API 描述文件时发现的结构性错误”相同。此验证不包括与 OpenAPI v3.0 JSON 架构的检查,这仅在 CLI 中实现。

// return `true` in case no errors have been found, `false` in case of errors.
$specValid = $openapi->validate();
// after validation getErrors() can be used to retrieve the list of errors found.
$errors = $openapi->getErrors();

注意:验证仅在非常基本的级别上执行,并不完整。因此,失败的验证将显示一些错误,但给出的错误列表可能不完整。此外,通过验证并不一定表明规范完全有效。

完整性

此库目前正在开发中,以下列表跟踪完整性

  • 读取 OpenAPI 3.0 JSON
  • 读取 OpenAPI 3.0 YAML
  • OpenAPI 3.0 架构
    • OpenAPI 对象
    • Info 对象
    • Contact 对象
    • License 对象
    • Server 对象
    • Server 变量对象
    • Components 对象
    • Paths 对象
    • Path Item 对象
    • Operation 对象
    • 外部文档对象
    • 参数对象
    • 请求体对象
    • 媒体类型对象
    • 编码对象
    • 响应对象
    • 响应体对象
    • 回调对象
    • 示例对象
    • 链接对象
    • 头部对象
    • 标签对象
    • 参考对象
    • 模式对象
      • 加载/读取
      • 验证
    • 判别器对象
    • XML对象
    • 安全方案对象
    • OAuth流程对象
    • OAuth流程对象
    • 安全需求对象

开发

您可以使用Docker环境进行本地开发

docker-compose build
make IN_DOCKER=1 install
make IN_DOCKER=1 test
...

支持

需要帮助您的API项目吗?

提供专业支持、咨询以及软件开发服务

https://www.cebe.cc/en/contact

本库的开发由cebe.:cloud: "您的专业部署平台"赞助。