ropi / json-schema-generator
JSON Schema 生成器
v0.2.1
2022-03-29 20:37 UTC
Requires
- php: >=8.1.0
- ext-mbstring: *
- ropi/cardinality-estimation: ^0.2
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-15 22:23:27 UTC
README
此库是基于 PHP 的 JSON Schemas 生成器的实现,可以轻松地使用自己的关键词和草案进行扩展。该库非常适合在实例/数据集众多的情况下,需要根据这些实例/数据集生成模式的情况。
以下草案原生支持
要求
- PHP ^8.1
安装
可以使用 composer 从命令行界面安装此库。
composer require ropi/json-schema-generator
基本用法
<?php $instances = [ (object) [ 'firstname' => 'Foo', 'age' => 18 ], (object) [ 'firstname' => 'Bar', 'age' => 29, 'country' => 'DE' ] ]; $config = new \Ropi\JsonSchemaGenerator\Config\GenerationConfig( draft: new \Ropi\JsonSchemaGenerator\Draft\Draft202012() ); $generator = new \Ropi\JsonSchemaGenerator\JsonSchemaGenerator($config); foreach ($instances as $instance) { $generator->recordInstance($instance); } echo json_encode($generator->generateSchema(), JSON_PRETTY_PRINT);
上述示例的输出
{ "$schema": "https:\/\/json-schema.org\/draft\/2020-12\/schema", "type": "object", "required": [ "firstname", "age" ], "properties": { "firstname": { "type": "string", "enum": [ "Foo", "Bar" ] }, "age": { "type": "integer", "enum": [ 18, 29 ] }, "country": { "type": "string", "enum": [ "DE" ] } }, "additionalProperties": false }
生成的模式尽可能严格。记录的实例越多,生成的模式越好。这里是一个带有更多实例的示例
<?php $instances = [ (object) [ 'firstname' => 'Foo', 'age' => 18 ], (object) [ 'firstname' => 'Bar', 'age' => 29, 'country' => 'DE' ], (object) [ 'firstname' => 'Abc', 'age' => 31, 'country' => 'DE' ], (object) [ 'firstname' => 'Def', 'age' => 44, 'country' => 'AT' ], (object) [ 'firstname' => 'Ghi', 'age' => 23, 'country' => 'FR' ], (object) [ 'firstname' => 'Jkl', 'age' => 33 ], (object) [ 'firstname' => 'Mnop', 'age' => 34 ], (object) [ 'firstname' => 'Qrstuvw', 'age' => 50 ], (object) [ 'firstname' => 'xyz', 'age' => 56 ] ]; $config = new \Ropi\JsonSchemaGenerator\Config\GenerationConfig( draft: new \Ropi\JsonSchemaGenerator\Draft\Draft202012(), maxEnumSize: 8 ); $generator = new \Ropi\JsonSchemaGenerator\JsonSchemaGenerator($config); foreach ($instances as $instance) { $generator->recordInstance($instance); } echo json_encode($generator->generateSchema(), JSON_PRETTY_PRINT);
上述示例的输出
{ "$schema": "https:\/\/json-schema.org\/draft\/2020-12\/schema", "type": "object", "required": [ "firstname", "age" ], "properties": { "firstname": { "type": "string", "minLength": 3, "maxLength": 7, "examples": [ "Foo", "Bar", "Abc", "Def", "Ghi", "Jkl", "Mnop", "Qrstuvw", "xyz" ] }, "age": { "type": "integer", "minimum": 18, "maximum": 56, "examples": [ 18, 29, 31, 44, 23, 33, 34, 50, 56 ] }, "country": { "type": "string", "enum": [ "DE", "AT", "FR" ] } }, "additionalProperties": false }