justinrainbow/json-schema

用于验证json schema的库。

安装次数: 227 762 512

依赖项: 602

建议者: 13

安全: 0

星标: 3 528

关注者: 54

分支: 350

开放问题: 29

6.0.0 2024-07-30 17:49 UTC

README

Build Status Latest Stable Version Total Downloads

这是一个PHP实现,用于验证给定Schema下的JSON结构,支持Draft-3或Draft-4的Schema。新版本Draft的功能可能不受支持。查看所有版本的表格以了解所有现有Draft的概述。

有关更多详细信息,请参阅json-schema

安装

git clone https://github.com/jsonrainbow/json-schema.git

Composer

安装PHP Composer

composer require justinrainbow/json-schema

使用

对于完整的参考,请参阅理解JSON Schema

注意: Draft-4之后的新版本的功能可能不受支持!

基本用法

<?php

$data = json_decode(file_get_contents('data.json'));

// Validate
$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);

if ($validator->isValid()) {
    echo "The supplied JSON validates against the schema.\n";
} else {
    echo "JSON does not validate. Violations:\n";
    foreach ($validator->getErrors() as $error) {
        printf("[%s] %s\n", $error['property'], $error['message']);
    }
}

类型强制转换

如果你通过HTTP将数据传递到你的应用程序进行验证,你可以将字符串和布尔值转换为你的schema中定义的预期类型

<?php

use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;
use JsonSchema\Constraints\Constraint;

$request = (object)[
    'processRefund'=>"true",
    'refundAmount'=>"17"
];

$validator->validate(
    $request, (object) [
    "type"=>"object",
        "properties"=>(object)[
            "processRefund"=>(object)[
                "type"=>"boolean"
            ],
            "refundAmount"=>(object)[
                "type"=>"number"
            ]
        ]
    ],
    Constraint::CHECK_MODE_COERCE_TYPES
); // validates!

is_bool($request->processRefund); // true
is_int($request->refundAmount); // true

还有一个简写方法可供选择

$validator->coerce($request, $schema);
// equivalent to $validator->validate($data, $schema, Constraint::CHECK_MODE_COERCE_TYPES);

默认值

如果你的schema包含默认值,你可以在验证过程中自动应用这些值

<?php

use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;

$request = (object)[
    'refundAmount'=>17
];

$validator = new Validator();

$validator->validate(
    $request,
    (object)[
        "type"=>"object",
        "properties"=>(object)[
            "processRefund"=>(object)[
                "type"=>"boolean",
                "default"=>true
            ]
        ]
    ],
    Constraint::CHECK_MODE_APPLY_DEFAULTS
); //validates, and sets defaults for missing properties

is_bool($request->processRefund); // true
$request->processRefund; // true

使用内联引用

<?php

use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;

$jsonSchema = <<<'JSON'
{
    "type": "object",
    "properties": {
        "data": {
            "oneOf": [
                { "$ref": "#/definitions/integerData" },
                { "$ref": "#/definitions/stringData" }
            ]
        }
    },
    "required": ["data"],
    "definitions": {
        "integerData" : {
            "type": "integer",
            "minimum" : 0
        },
        "stringData" : {
            "type": "string"
        }
    }
}
JSON;

// Schema must be decoded before it can be used for validation
$jsonSchemaObject = json_decode($jsonSchema);

// The SchemaStorage can resolve references, loading additional schemas from file as needed, etc.
$schemaStorage = new SchemaStorage();

// This does two things:
// 1) Mutates $jsonSchemaObject to normalize the references (to file://mySchema#/definitions/integerData, etc)
// 2) Tells $schemaStorage that references to file://mySchema... should be resolved by looking in $jsonSchemaObject
$schemaStorage->addSchema('file://mySchema', $jsonSchemaObject);

// Provide $schemaStorage to the Validator so that references can be resolved during validation
$jsonValidator = new Validator(new Factory($schemaStorage));

// JSON must be decoded before it can be validated
$jsonToValidateObject = json_decode('{"data":123}');

// Do validation (use isValid() and getErrors() to check the result)
$jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject);

配置选项

有一些标志可以用来改变验证器的行为。这些可以作为第三个参数传递给Validator::validate(),或者作为第三个参数传递给Factory::__construct(),如果你希望它们在多个validate()调用中持续存在。

请注意,使用CHECK_MODE_COERCE_TYPESCHECK_MODE_APPLY_DEFAULTS将修改你的原始数据。

CHECK_MODE_EARLY_COERCE除非与CHECK_MODE_COERCE_TYPES一起使用,否则没有效果。如果启用,验证器将使用(并强制转换)它遇到的第一个兼容类型,即使schema定义了另一个类型并且不需要强制转换。

运行测试

composer test                            # run all unit tests
composer testOnly TestClass              # run specific unit test class
composer testOnly TestClass::testMethod  # run specific unit test method
composer style-check                     # check code style for errors
composer style-fix                       # automatically fix code style errors