1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
|
# JSON Schema for PHP
[](https://github.com/jsonrainbow/json-schema/actions)
[](https://packagist.org/packages/justinrainbow/json-schema)
[](https://packagist.org/packages/justinrainbow/json-schema/stats)
A PHP Implementation for validating `JSON` Structures against a given `Schema` with support for `Schemas` of Draft-3 or Draft-4. Features of newer Drafts might not be supported. See [Table of All Versions of Everything](https://json-schema.org/specification-links.html#table-of-all-versions-of-everything) to get an overview of all existing Drafts.
See [json-schema](http://json-schema.org/) for more details.
## Installation
### Library
```bash
git clone https://github.com/jsonrainbow/json-schema.git
```
### Composer
[Install PHP Composer](https://getcomposer.org/doc/00-intro.md)
```bash
composer require justinrainbow/json-schema
```
## Usage
For a complete reference see [Understanding JSON Schema](https://json-schema.org/understanding-json-schema/).
__Note:__ features of Drafts newer than Draft-4 might not be supported!
### Basic usage
```php
<?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) {
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
<?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:
```PHP
$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
<?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
<?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` | Convert data types to match the schema where possible |
| `Constraint::CHECK_MODE_EARLY_COERCE` | Apply type coercion as soon as possible |
| `Constraint::CHECK_MODE_APPLY_DEFAULTS` | 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 |
Please note that using `CHECK_MODE_COERCE_TYPES` or `CHECK_MODE_APPLY_DEFAULTS` will modify your
original data.
`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.
## Running the tests
```bash
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.
<a href="https://github.com/jsonrainbow/json-schema/graphs/contributors">
<img src="https://contrib.rocks/image?repo=jsonrainbow/json-schema" />
</a>
|