evaisse/php-json-schema-generator

JSON Schema 生成器。

v2.1.0 2022-06-24 09:39 UTC

This package is auto-updated.

Last update: 2024-08-24 14:42:48 UTC


README

Build Status codecov

最初是从 solvire/php-json-schema-generator 分支出来的

以下是 json schema 的介绍(以及工具)

要验证您的结构是否符合给定的模式,可以使用

快速入门

使用 composer 安装

composer require evaisse/php-json-schema-generator

最简单的情况

$output = JSONSchemaGenerator\Generator::fromJson('{"a":{"b":2}');
 
// $output ==> json string
// {
//   "$schema": "https://json-schema.fullstack.org.cn/draft-04/schema#",
//   "type": "object",
//   "properties": {
//     "a": {
//       "type": "object",
//       "properties": {
//         "b": {
//           "type": "integer"
//         }
//       },
//       "required": ["b"]
//     }
//   },
//   "required": ["a"]
// }

默认配置值

[
    'schema_id'                      => null,
    'properties_required_by_default' => true,
    'schema_uri'                     => 'https://json-schema.fullstack.org.cn/draft-04/schema#',
    'schema_title'                   => null,
    'schema_description'             => null,
    'schema_type'                    => null,
    "items_schema_collect_mode"      => 0,
    'schema_required_field_names'    => []
]

高级用法

$result = Generator::fromJson($this->addressJson1, [
    'schema_id' => 'http://foo.bar/schema'
]);

/*

  {
    "$schema": "https://json-schema.fullstack.org.cn/draft-04/schema#",
    "id": "http://foo.bar/schema",
    "type": "object",
    "properties": {
      "a": {
        "type": "object",
        "id": "http://foo.bar/schema/a",
        "properties": {
          "b": {
            "id": "http://foo.bar/schema/a/b",
            "type": "integer"
          }
        }
      }
    }

*/


// if you want items as strict lists instead of "anyOf" type
$result = Generator::fromJson($this->addressJson1, [
    'schema_id'                      => 'http://bar.foo/schema2',
    'schema_title'                   => 'coucouc',
    'schema_description'             => 'desc',
    "items_schema_collect_mode"      => Definition::ITEMS_AS_LIST,
]);

/*
    {
        "$schema":"http:\/\/json-schema.org\/draft-04\/schema#",
        ...
        "properties": {
            "phoneNumber":{
                "id":"http:\/\/bar.foo\/schema2\/phoneNumber",
                "type":"array",
                "items": [ 
                    {"id":"http:\/\/bar.foo\/schema2\/0",...},
                    {"id":"http:\/\/bar.foo\/schema2\/1",...}}
*/

对于更高级的用法,请参阅 tests/JSONSchemaGenerator/Tests/GeneratorTest.php

测试

只需运行 phpunit 通过

composer test

调试使用

DEBUG=true composer test -- --filter="SearchWord" # for filtering *SearchWord* test case with output debugging

路线图

  • 调整模式比较,通过属性重排序来比较两个模式,而不是仅仅比较它们的 JSON 形式。例如 { a: 1, b: 2 }{ b: 2, a: 1 } 应该产生相同的模式。

  • 提供在大多数字段中允许 null 值的选项 ("type": ["string", "null"]}