cmpayments/schemavalidator

SchemaValidator 是一个针对 Schema(也可以是字符串)验证 JSON 的 PHP 实现,JSON 和 Schema 都通过 https://github.com/cmpayments/jsonlint 进行了 linting。这个库针对速度和性能进行了优化。

v0.1.1 2017-02-02 15:04 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:20:43 UTC


README

License Latest Stable Version Scrutinizer Code Quality Total Downloads Reference Status

SchemaValidator 是一个用于验证 JSON 与 Schema(也可以是字符串)的 PHP 实现,JSON 和 Schema 都使用 https://github.com/cmpayments/jsonlint 进行了 linting。这个库针对速度和性能进行了优化。

安装

要使用 Composer 快速安装,请使用

$ composer require cmpayments/schemavalidator

如果你有一个 PSR-4 自动加载器,则可以轻松地在另一个应用程序中使用 Schema Validator for PHP,或者可以通过 Composer 安装。

用法

// use the required classes

use CMPayments\Cache\Cache;
use CMPayments\Json\Json;
use CMPayments\SchemaValidator\SchemaValidator;;

示例 #1 - 简单;验证 JSON 输入的语法错误

$data = '{"testProperty": {"length": 7.0, "superfluousProperty": 12.0}}';

// the constructor only accepts Strings as input
$json = new Json($data);

// validate() returns a boolean whether the $data input is valid JSON or not
$isValid = $json->validate(); // $isValid = true since we only want to know if $data is valid JSON or not (we are not validating any schema's yet)

var_dump('Example 1:', $isValid); // true

示例 #2 - 高级;验证 JSON 输入的语法错误,并验证 JSON 是否符合 Schema

$data   = '{"testProperty": {"length": 7, "superfluousProperty": 12.0}}';
$schema = '{"type": "object","properties": {"testProperty": {"type": "object","properties": {"length": {"type": "number"}}}},"additionalProperties": true}';

$json = new Json($data);

// validate()' first argument only accepts Strings , the second parameter is a passthru parameter which picks up error along the way (if any)
$isValid = $json->validate($schema, $errors);

if ($isValid) { // $isValid = true since additional properties are now allowed

    // Get the decoded version of the $input (which was a String when inputted)
    var_dump('Example 2:', $json->getDecodedJSON()); // returns:

//    object(stdClass)[11]
//      public 'testProperty' =>
//        object(stdClass)[10]
//          public 'length' => float 7
//          public 'superfluousProperty' => float 12
} else {

    // in case $isValid should be false, $errors is the passthru variable and it now contains an array with all the errors that occurred.
    var_dump($errors);
}

// example data for example 3 & 4
$data   = '{"testProperty": {"length": 7.0, "superfluousProperty": 12.0}}';
$schema = '{"type": "object","properties": {"testProperty": {"type": "object","properties": {"length": {"type": "number"}}}},"additionalProperties": false}';

示例 #3 - 简单 SchemaValidator 示例;如果你对 JSON(字符串)是否有效不感兴趣(因为输入是对象)

// SchemaValidator constructor:
// first argument is the JSON input and only accepts it when it is an object (mandatory)
// second argument is the Schema input and only accepts it when it is an object (mandatory)
// third argument must be an instance of Cache() (optional)
try {

    $validator = new SchemaValidator(json_decode($data), json_decode($schema));

    if (!$validator->isValid()) { // returns false again additional properties are not allowed

        var_dump('Example 3:', $validator->getErrors()); // returns:

//        array(size = 1)
//          0 =>
//            array(size = 3)
//              'code' => int 101
//              'args' => string '/testProperty/superfluousProperty' (length = 33)
//              'message' => string 'The Data property ' / testProperty / superfluousProperty' is not an allowed property' (length = 80)
    }
} catch (\Exception $e) {

    var_dump('Example 3:', $e->getMessage());
}

示例 #4 - 高级 SchemaValidator 示例;如果你对 JSON(字符串)是否有效不感兴趣(因为输入是对象),但你想要指定一些缓存选项

try {

    // create new Cache object
    $cache = new Cache();

    // There are currently 2 cache options that can be set
    // 'debug' (boolean), if true you'll be notified if your cache directory is writable or not (any validation will be considered false when the cache directory is not writable and debug is true).
    // 'directory' (string), the absolute location where the cached schema's should be stored, by default this is '/src/CMPayments/SchemaValidator/cache/'
    $cache->setOptions(['debug' => true, 'directory' => 'absolute/path/to/your/cache/directory']); // currently this does not exist yet

    $validator = new SchemaValidator(json_decode($data), json_decode($schema), $cache);

    if (!$validator->isValid()) { // returns false again additional properties are not allowed but firstly because the current cache directory 'absolute/path/to/your/cache/directory' is not writable (since it doesn't exist).

        var_dump('Example 4:', (!$validator->isValid() ? 'false' : 'true'));
        //var_dump($validator->getErrors());
    }
} catch (\Exception $e) {

    var_dump('Example 4: ', $validator->isValid(), $e->getMessage()); // false, The cache directory 'absolute/path/to/your/cache/directory' is not writable
}

其他示例

示例;当输入是数组时测试输入

try {

    $data   = ["length" => 7.0, "superfluousProperty" => 12.0];
    $schema = '{"type": "array","items": {"type": "number"}}';

    $validator = new SchemaValidator((($data)), json_decode($schema));

    var_dump('Example 5:', $validator->isValid()); // true
    //var_dump($validator->getErrors());
} catch (\Exception $e) {

    var_dump('Example 5', $e->getMessage());
}

示例;当输入是布尔值时测试输入

try {

    $data   = true;
    $schema = '{"type": "boolean"}';

    $validator = new SchemaValidator((($data)), json_decode($schema));

    var_dump('Example 6:', $validator->isValid());  // true
//    var_dump($validator->getErrors());
} catch (\Exception $e) {

    var_dump('Example 6:', $e->getMessage());
}

示例;当输入是数字(浮点数)时测试输入

try {

    $data   = 1.4;
    $schema = '{"type": "boolean"}';

    $validator = new SchemaValidator((($data)), json_decode($schema));

    var_dump('Example 7:', $validator->isValid());  // false
    var_dump($validator->getErrors()); // message reads: The Data property '/' needs to be a 'boolean' but got a 'number' (with value '1.4')
} catch (\Exception $e) {

    var_dump('Example 7:', $e->getMessage());
}

示例;当输入是数字(整数)时测试输入

try {

    $data   = 22;
    $schema = '{"type": "number"}';

    $validator = new SchemaValidator((($data)), json_decode($schema));

    var_dump('Example 8:', $validator->isValid());  // true
    //var_dump($validator->getErrors());
} catch (\Exception $e) {

    var_dump('Example 8:', $e->getMessage());
}

示例;当输入是字符串时测试输入

try {

    $data   = 'test12345';
    $schema = '{"type": "string"}';

    $validator = new SchemaValidator((($data)), json_decode($schema));

    var_dump('Example 9:', $validator->isValid());  // true
//    var_dump($validator->getErrors());
} catch (\Exception $e) {

    var_dump('Example 9:', $e->getMessage());
}

// Example; simple one-line example
$isValid = (new Json('true'))->validate(null, $errors);
(var_dump('Example 10: ', $isValid, $errors));

要求

  • PHP 5.4+
  • [可选] PHPUnit 3.5+ 以执行测试套件(phpunit --version)

提交错误和功能请求

错误和功能请求在 GitHub 上跟踪

待办事项

作者

Boy Wijnmaalen - boy.wijnmaalen@cmtelecom.com - https://twitter.com/boywijnmaalen

许可证

Schema Validator 在 MIT 许可证下授权 - 有关详细信息,请参阅 LICENSE 文件