承接 justinrainbow/json-schema 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

justinrainbow/json-schema

Composer 安装命令:

composer require justinrainbow/json-schema

包简介

A library to validate a json schema.

关键字:

README 文档

README

Build Status Latest Stable Version Total Downloads Supported Dialects

A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3, Draft-4, Draft-6,Draft-7 or Draft 2019-09.

Features of newer Drafts might not be supported. See Table of All Versions of Everything to get an overview of all existing Drafts. See json-schema for more details about the JSON Schema specification

Compliance

Draft 3 Draft 4 Draft 6 Draft 7)) Draft 2019-09

Installation

Library

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

Composer

Install PHP Composer

composer require justinrainbow/json-schema

Usage

For a complete reference see Understanding JSON Schema.

Note: Not all drafts might be supported, check the Bowtie report on the current state of draft implementations.

Basic usage

<?php

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

// 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']);
    }
}

Type coercion

If you're validating data passed to your application via HTTP, you can cast strings and booleans to the expected types defined by your 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

A shorthand method is also available:

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

Default values

If your schema contains default values, you can have these automatically applied during validation:

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

With inline references

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

Configuration Options

A number of flags are available to alter the behavior of the validator. These can be passed as the third argument to Validator::validate(), or can be provided as the third argument to Factory::__construct() if you wish to persist them across multiple validate() calls.

Flag Description
Constraint::CHECK_MODE_NORMAL Validate in 'normal' mode - this is the default
Constraint::CHECK_MODE_TYPE_CAST Enable fuzzy type checking for associative arrays and objects
Constraint::CHECK_MODE_COERCE_TYPES 12 Convert data types to match the schema where possible
Constraint::CHECK_MODE_EARLY_COERCE 2 Apply type coercion as soon as possible
Constraint::CHECK_MODE_APPLY_DEFAULTS 1 Apply default values from the schema if not set
Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS When applying defaults, only set values that are required
Constraint::CHECK_MODE_EXCEPTIONS Throw an exception immediately if validation fails
Constraint::CHECK_MODE_DISABLE_FORMAT Do not validate "format" constraints
Constraint::CHECK_MODE_VALIDATE_SCHEMA Validate the schema as well as the provided document
Constraint::CHECK_MODE_STRICT 3 Validate the scheme using strict mode using the specified draft

Running the tests

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

Contributors ✨

Thanks go to these wonderful people, without their effort this project wasn't possible.

Footnotes

  1. Please note that using CHECK_MODE_COERCE_TYPES or CHECK_MODE_APPLY_DEFAULTS will modify your original data. 2

  2. CHECK_MODE_EARLY_COERCE has no effect unless used in combination with CHECK_MODE_COERCE_TYPES. If enabled, the validator will use (and coerce) the first compatible type it encounters, even if the schema defines another type that matches directly and does not require coercion. 2

  3. CHECK_MODE_STRICT only can be used for Draft-6, Draft 7 or Draft 2019-09 at this point.

justinrainbow/json-schema 适用场景与选型建议

justinrainbow/json-schema 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 331.48M 次下载、GitHub Stars 达 3.63k, 最近一次更新时间为 2011 年 12 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「schema」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 justinrainbow/json-schema 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 justinrainbow/json-schema 我们能提供哪些服务?
定制开发 / 二次开发

基于 justinrainbow/json-schema 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 331.48M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3679
  • 点击次数: 14
  • 依赖项目数: 682
  • 推荐数: 19

GitHub 信息

  • Stars: 3631
  • Watchers: 45
  • Forks: 369
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2011-12-10