pxhub/php-json-schema-generator

v1.0.3 2023-12-20 20:58 UTC

This package is not auto-updated.

Last update: 2024-09-26 00:37:04 UTC


README

Build Status codecov

最初从 evaisse/php-json-schema-generator 分支而来

变更列表

  • 收集每个标量类型的示例。
  • 将项目属性合并到单个列表中,而不是 'anyOf' 列表中。

以下为 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 properties list
$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 } 应该产生相同的模式。

  • 提供一个选项以允许大多数字段允许空值 ("type": ["string", "null"]}