robotdance/php-json-schema

该软件包已被废弃,不再维护。作者建议使用php-json-schema软件包代替。

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

v2.1.1 2016-06-29 20:14 UTC

README

Code Climate Test Coverage Issue Count Build Status

这是一个PHP实现的json-schema,用于验证JSON数据是否符合JSON Schema定义。

最初是从justinrainbow/json-schema分叉的。

除了原始版本,还添加了国际化验证消息,初始支持en-US和pt-BR。目前,"add-i18n"分支将与分叉的仓库保持同步,而master分支将走自己的路。

安装

PHP-Json-Schema可以作为Composer软件包使用,同时使用它作为其依赖管理器。因此,您需要在项目根目录中有一个composer.json文件,并要求php-json-schema

  ...
  "require": {
    "robotdance/php-json-schema": "latest stable version"
  }
  ...

因此,在更新您的composer文件后,只需更新composer。

$ php composer.phar update
$ composer update

您使用composer更新的方式将取决于您如何安装composer。

使用

<?php

// Get the schema and data as objects
// If you use $ref or if you are unsure, resolve those references here
// This modifies the $schema object
$refResolver = new JsonSchema\RefResolver(new JsonSchema\Uri\UriRetriever(), new JsonSchema\Uri\UriResolver());
$schema = $refResolver->resolve('file://' . realpath('schema.json'));

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

// Validate
$validator = new JsonSchema\Validator();
$validator->check($data, $schema);

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

运行测试

$ vendor/bin/phpunit