neofonie/json-schema

此包已被废弃且不再维护。未建议替代包。

一个用于验证json模式的库。

5.2.9 2019-09-25 14:49 UTC

README

⚠️ 此项目现已停维护且处于只读模式 ⚠️

Build Status Latest Stable Version Total Downloads

一个用于验证与给定 Schema 相对应的 JSON 结构的PHP实现。

有关更多详情,请参阅 json-schema

安装

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

Composer

安装PHP Composer

composer require justinrainbow/json-schema

使用方法

<?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) {
        echo sprintf("[%s] %s\n", $error['property'], $error['message']);
    }
}

类型转换

如果您正在验证通过HTTP传递给应用程序的数据,您可以转换字符串和布尔值以符合您模式中定义的预期类型

<?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);

默认值

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

<?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() 的第三个参数传递,或者如果您希望跨多个 validate() 调用持久化它们,则可以作为 Factory::__construct() 的第三个参数提供。

标志 描述
Constraint::CHECK_MODE_NORMAL 在 '正常' 模式下进行验证 - 这是默认模式
Constraint::CHECK_MODE_TYPE_CAST 启用关联数组和对象的模糊类型检查
Constraint::CHECK_MODE_COERCE_TYPES 尽可能将数据类型转换为与模式匹配的类型
Constraint::CHECK_MODE_EARLY_COERCE 尽可能早地应用类型转换
Constraint::CHECK_MODE_APPLY_DEFAULTS 如果未设置,则应用模式中的默认值
Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS 应用默认值时,仅设置所需值
Constraint::CHECK_MODE_EXCEPTIONS 验证失败时立即抛出异常
Constraint::CHECK_MODE_DISABLE_FORMAT 不要验证 "格式" 约束
Constraint::CHECK_MODE_VALIDATE_SCHEMA 验证提供的文档以及模式

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

CHECK_MODE_EARLY_COERCE 只有在与 CHECK_MODE_COERCE_TYPES 结合使用时才有作用。如果启用,验证器将使用(并转换)它遇到的第一个兼容类型,即使模式定义了另一个直接匹配且不需要转换的类型。

运行测试

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