riley19280/fluent-json-schema

轻松创建JSON模式

v1.2.1 2024-08-27 17:31 UTC

This package is auto-updated.

Last update: 2024-09-27 17:41:45 UTC


README

轻松创建JSON模式

安装

composer require riley19280/fluent-json-schema

基本用法

use FluentJsonSchema\FluentSchema;

$schema = FluentSchema::make()
    ->type()->object()
    ->property('name', FluentSchema::make()
        ->type()->string()
    )
    ->return()
    ->compile();
/* Results in
{
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        }
    }
}
*/

更多高级用法可以在这里找到。该包已经实现了整个元模式规范。

上下文

在构建JSON模式对象时,您可能处于几种不同的“上下文”之一。这些是主要的数据类型上下文:

  • 数组
  • 整数
  • 数字
  • 对象
  • 字符串

它们都有不同的方法来设置与该数据类型相关的特定属性。如果您需要在任何时候返回到“全局”上下文,您可以调用return方法。

布尔模式

在某些情况下,需要一个评估为truefalse的模式,您可以传递FluentSchema::make()->true()FluentSchema::make()->false()

FluentSchema::make()
    ->type()->object()
    ->additionalProperties(FluentSchema::make()->false())

转换为JSON

构建完您的模式对象后,调用其上的compile方法。这将返回一个PHP数组,您可以将它序列化为JSON。

默认情况下,属性将按照它们添加到对象中的顺序进行序列化,即:

$schema = FluentSchema::make()->schema('schema')->id('id')->compile();
// Will be
// { "$schema": "schema", "$id": "id" }
$schema = FluentSchema::make()->id('id')->schema('schema')->compile();
// Will be
// { "$id": "id", "$schema": "schema" }

可以通过调用$schema->getSchemaDTO()->setKeyOrder(['$id', '$schema'])来更改此顺序。这将覆盖序列化顺序。任何未列出的键将添加到末尾。

验证

验证使用justinrainbow/json-schema包进行。

FluentSchema对象上提供了以下方法来帮助进行模式验证:

  • getSchemaStorage(): SchemaStorage
  • setSchemaStorage(SchemaStorage $schemaStorage): static
  • validate(mixed &$data, int $checkMode = null): Validator
  • addValidationSchema(object|array $schema, string $id = null): static
$isValid = FluentSchema::make()
    ->type()->object()
    ->property('name', FluentSchema::make()
        ->type()->string()
    )
    ->return()
    ->validate((object)[
        'name' => 'validated!',
    ])
    ->isValid();

有关验证的更详细信息,请参阅justinrainbow/json-schema包文档。