| 1 |
# JSON Schema for PHP |
| 2 |
|
| 3 |
[](https://travis-ci.org/justinrainbow/json-schema) |
| 4 |
[](https://packagist.org/packages/justinrainbow/json-schema) |
| 5 |
[](https://packagist.org/packages/justinrainbow/json-schema) |
| 6 |
|
| 7 |
A PHP Implementation for validating `JSON` Structures against a given `Schema`. |
| 8 |
|
| 9 |
See [json-schema](http://json-schema.org/) for more details. |
| 10 |
|
| 11 |
## Installation |
| 12 |
|
| 13 |
### Library |
| 14 |
|
| 15 |
```bash |
| 16 |
git clone https://github.com/justinrainbow/json-schema.git |
| 17 |
``` |
| 18 |
|
| 19 |
### Composer |
| 20 |
|
| 21 |
[Install PHP Composer](https://getcomposer.org/doc/00-intro.md) |
| 22 |
|
| 23 |
```bash |
| 24 |
composer require justinrainbow/json-schema |
| 25 |
``` |
| 26 |
|
| 27 |
## Usage |
| 28 |
|
| 29 |
```php |
| 30 |
<?php |
| 31 |
|
| 32 |
$data = json_decode(file_get_contents('data.json')); |
| 33 |
|
| 34 |
// Validate |
| 35 |
$validator = new JsonSchema\Validator; |
| 36 |
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]); |
| 37 |
|
| 38 |
if ($validator->isValid()) { |
| 39 |
echo "The supplied JSON validates against the schema.\n"; |
| 40 |
} else { |
| 41 |
echo "JSON does not validate. Violations:\n"; |
| 42 |
foreach ($validator->getErrors() as $error) { |
| 43 |
echo sprintf("[%s] %s\n", $error['property'], $error['message']); |
| 44 |
} |
| 45 |
} |
| 46 |
``` |
| 47 |
|
| 48 |
### Type coercion |
| 49 |
|
| 50 |
If you're validating data passed to your application via HTTP, you can cast strings and booleans to |
| 51 |
the expected types defined by your schema: |
| 52 |
|
| 53 |
```php |
| 54 |
<?php |
| 55 |
|
| 56 |
use JsonSchema\SchemaStorage; |
| 57 |
use JsonSchema\Validator; |
| 58 |
use JsonSchema\Constraints\Factory; |
| 59 |
use JsonSchema\Constraints\Constraint; |
| 60 |
|
| 61 |
$request = (object)[ |
| 62 |
'processRefund'=>"true", |
| 63 |
'refundAmount'=>"17" |
| 64 |
]; |
| 65 |
|
| 66 |
$validator->validate( |
| 67 |
$request, (object) [ |
| 68 |
"type"=>"object", |
| 69 |
"properties"=>(object)[ |
| 70 |
"processRefund"=>(object)[ |
| 71 |
"type"=>"boolean" |
| 72 |
], |
| 73 |
"refundAmount"=>(object)[ |
| 74 |
"type"=>"number" |
| 75 |
] |
| 76 |
] |
| 77 |
], |
| 78 |
Constraint::CHECK_MODE_COERCE_TYPES |
| 79 |
); // validates! |
| 80 |
|
| 81 |
is_bool($request->processRefund); // true |
| 82 |
is_int($request->refundAmount); // true |
| 83 |
``` |
| 84 |
|
| 85 |
A shorthand method is also available: |
| 86 |
```PHP |
| 87 |
$validator->coerce($request, $schema); |
| 88 |
// equivalent to $validator->validate($data, $schema, Constraint::CHECK_MODE_COERCE_TYPES); |
| 89 |
``` |
| 90 |
|
| 91 |
### Default values |
| 92 |
|
| 93 |
If your schema contains default values, you can have these automatically applied during validation: |
| 94 |
|
| 95 |
```php |
| 96 |
<?php |
| 97 |
|
| 98 |
use JsonSchema\Validator; |
| 99 |
use JsonSchema\Constraints\Constraint; |
| 100 |
|
| 101 |
$request = (object)[ |
| 102 |
'refundAmount'=>17 |
| 103 |
]; |
| 104 |
|
| 105 |
$validator = new Validator(); |
| 106 |
|
| 107 |
$validator->validate( |
| 108 |
$request, |
| 109 |
(object)[ |
| 110 |
"type"=>"object", |
| 111 |
"properties"=>(object)[ |
| 112 |
"processRefund"=>(object)[ |
| 113 |
"type"=>"boolean", |
| 114 |
"default"=>true |
| 115 |
] |
| 116 |
] |
| 117 |
], |
| 118 |
Constraint::CHECK_MODE_APPLY_DEFAULTS |
| 119 |
); //validates, and sets defaults for missing properties |
| 120 |
|
| 121 |
is_bool($request->processRefund); // true |
| 122 |
$request->processRefund; // true |
| 123 |
``` |
| 124 |
|
| 125 |
### With inline references |
| 126 |
|
| 127 |
```php |
| 128 |
<?php |
| 129 |
|
| 130 |
use JsonSchema\SchemaStorage; |
| 131 |
use JsonSchema\Validator; |
| 132 |
use JsonSchema\Constraints\Factory; |
| 133 |
|
| 134 |
$jsonSchema = <<<'JSON' |
| 135 |
{ |
| 136 |
"type": "object", |
| 137 |
"properties": { |
| 138 |
"data": { |
| 139 |
"oneOf": [ |
| 140 |
{ "$ref": "#/definitions/integerData" }, |
| 141 |
{ "$ref": "#/definitions/stringData" } |
| 142 |
] |
| 143 |
} |
| 144 |
}, |
| 145 |
"required": ["data"], |
| 146 |
"definitions": { |
| 147 |
"integerData" : { |
| 148 |
"type": "integer", |
| 149 |
"minimum" : 0 |
| 150 |
}, |
| 151 |
"stringData" : { |
| 152 |
"type": "string" |
| 153 |
} |
| 154 |
} |
| 155 |
} |
| 156 |
JSON; |
| 157 |
|
| 158 |
// Schema must be decoded before it can be used for validation |
| 159 |
$jsonSchemaObject = json_decode($jsonSchema); |
| 160 |
|
| 161 |
// The SchemaStorage can resolve references, loading additional schemas from file as needed, etc. |
| 162 |
$schemaStorage = new SchemaStorage(); |
| 163 |
|
| 164 |
// This does two things: |
| 165 |
// 1) Mutates $jsonSchemaObject to normalize the references (to file://mySchema#/definitions/integerData, etc) |
| 166 |
// 2) Tells $schemaStorage that references to file://mySchema... should be resolved by looking in $jsonSchemaObject |
| 167 |
$schemaStorage->addSchema('file://mySchema', $jsonSchemaObject); |
| 168 |
|
| 169 |
// Provide $schemaStorage to the Validator so that references can be resolved during validation |
| 170 |
$jsonValidator = new Validator( new Factory($schemaStorage)); |
| 171 |
|
| 172 |
// JSON must be decoded before it can be validated |
| 173 |
$jsonToValidateObject = json_decode('{"data":123}'); |
| 174 |
|
| 175 |
// Do validation (use isValid() and getErrors() to check the result) |
| 176 |
$jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject); |
| 177 |
``` |
| 178 |
|
| 179 |
### Configuration Options |
| 180 |
A number of flags are available to alter the behavior of the validator. These can be passed as the |
| 181 |
third argument to `Validator::validate()`, or can be provided as the third argument to |
| 182 |
`Factory::__construct()` if you wish to persist them across multiple `validate()` calls. |
| 183 |
|
| 184 |
| Flag | Description | |
| 185 |
|------|-------------| |
| 186 |
| `Constraint::CHECK_MODE_NORMAL` | Validate in 'normal' mode - this is the default | |
| 187 |
| `Constraint::CHECK_MODE_TYPE_CAST` | Enable fuzzy type checking for associative arrays and objects | |
| 188 |
| `Constraint::CHECK_MODE_COERCE_TYPES` | Convert data types to match the schema where possible | |
| 189 |
| `Constraint::CHECK_MODE_APPLY_DEFAULTS` | Apply default values from the schema if not set | |
| 190 |
| `Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS` | When applying defaults, only set values that are required | |
| 191 |
| `Constraint::CHECK_MODE_EXCEPTIONS` | Throw an exception immediately if validation fails | |
| 192 |
| `Constraint::CHECK_MODE_DISABLE_FORMAT` | Do not validate "format" constraints | |
| 193 |
| `Constraint::CHECK_MODE_VALIDATE_SCHEMA` | Validate the schema as well as the provided document | |
| 194 |
|
| 195 |
Please note that using `Constraint::CHECK_MODE_COERCE_TYPES` or `Constraint::CHECK_MODE_APPLY_DEFAULTS` |
| 196 |
will modify your original data. |
| 197 |
|
| 198 |
## Running the tests |
| 199 |
|
| 200 |
```bash |
| 201 |
composer test # run all unit tests |
| 202 |
composer testOnly TestClass # run specific unit test class |
| 203 |
composer testOnly TestClass::testMethod # run specific unit test method |
| 204 |
composer style-check # check code style for errors |
| 205 |
composer style-fix # automatically fix code style errors |
| 206 |
``` |