zerifas / json
There is no license information available for the latest version (3.0.0) of this package.
Define a schema for your JSON documents, and validate them
3.0.0
2022-12-15 21:35 UTC
Requires
- php: >=8.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.5
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-11-16 01:35:56 UTC
README
This is a small library allowing you to define a schema for your JSON documents, validate them, and get a "safe" version of the document, with all optional values set to their defaults.
Installation
Use composer:
$ composer required zerifas/json
Usage
<?php require 'vendor/autoload.php'; use Zerifas\JSON; $schema = new JSON\Obj([ 'id' => new JSON\Number(), 'enabled' => new JSON\OptionalBoolean(false), 'array' => new JSON\Arr(), 'stringArray' => new JSON\Arr(new JSON\Str()), 'optionalArray' => new JSON\OptionalArr(), 'optionalStringArray' => new JSON\OptionalArr(new JSON\Str()), 'optionalObj' => new JSON\OptionalObj( [ 'name' => new JSON\Str(), ], [ 'name' => 'Alice', ] ), ]); $v = new JSON\Validator($schema); $json = '{"id":1,"array":[],"stringArray":["Hello","World"]}'; if ($v->isValid($json)) { $doc = $v->getDocument(); echo implode(', ', $doc->stringArray), PHP_EOL; // Hello, World echo $doc->optionalObj->name, PHP_EOL; // Alice } // This is not valid for 2 reasons: `id` is missing, and `array` is a number. $json = '{"array":15,"stringArray":[]}'; if (!$v->isValid($json)) { // Errors will be an array: // [ // 'Key path \'id\' is required, but missing.', // 'Key path \'array\' should be array, but is number.', // ] foreach ($v->getErrors() as $err) { echo $err, PHP_EOL; } }