3 [![Build Status](https://travis-ci.org/justinrainbow/json-schema.svg?branch=master)](https://travis-ci.org/justinrainbow/json-schema)
4 [![Latest Stable Version](https://poser.pugx.org/justinrainbow/json-schema/v/stable.png)](https://packagist.org/packages/justinrainbow/json-schema)
5 [![Total Downloads](https://poser.pugx.org/justinrainbow/json-schema/downloads.png)](https://packagist.org/packages/justinrainbow/json-schema)
7 A PHP Implementation for validating `JSON` Structures against a given `Schema`.
9 See [json-schema](http://json-schema.org/) for more details.
16 git clone https://github.com/justinrainbow/json-schema.git
21 [Install PHP Composer](https://getcomposer.org/doc/00-intro.md)
24 composer require justinrainbow/json-schema
32 $data = json_decode(file_get_contents('data.json'));
35 $validator = new JsonSchema\Validator;
36 $validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);
38 if ($validator->isValid()) {
39 echo "The supplied JSON validates against the schema.\n";
41 echo "JSON does not validate. Violations:\n";
42 foreach ($validator->getErrors() as $error) {
43 echo sprintf("[%s] %s\n", $error['property'], $error['message']);
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:
56 use JsonSchema\SchemaStorage;
57 use JsonSchema\Validator;
58 use JsonSchema\Constraints\Factory;
59 use JsonSchema\Constraints\Constraint;
62 'processRefund'=>"true",
69 "properties"=>(object)[
70 "processRefund"=>(object)[
73 "refundAmount"=>(object)[
78 Constraint::CHECK_MODE_COERCE_TYPES
81 is_bool($request->processRefund); // true
82 is_int($request->refundAmount); // true
85 A shorthand method is also available:
87 $validator->coerce($request, $schema);
88 // equivalent to $validator->validate($data, $schema, Constraint::CHECK_MODE_COERCE_TYPES);
93 If your schema contains default values, you can have these automatically applied during validation:
98 use JsonSchema\Validator;
99 use JsonSchema\Constraints\Constraint;
105 $validator = new Validator();
107 $validator->validate(
111 "properties"=>(object)[
112 "processRefund"=>(object)[
118 Constraint::CHECK_MODE_APPLY_DEFAULTS
119 ); //validates, and sets defaults for missing properties
121 is_bool($request->processRefund); // true
122 $request->processRefund; // true
125 ### With inline references
130 use JsonSchema\SchemaStorage;
131 use JsonSchema\Validator;
132 use JsonSchema\Constraints\Factory;
134 $jsonSchema = <<<'JSON'
140 { "$ref": "#/definitions/integerData" },
141 { "$ref": "#/definitions/stringData" }
145 "required": ["data"],
158 // Schema must be decoded before it can be used for validation
159 $jsonSchemaObject = json_decode($jsonSchema);
161 // The SchemaStorage can resolve references, loading additional schemas from file as needed, etc.
162 $schemaStorage = new SchemaStorage();
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);
169 // Provide $schemaStorage to the Validator so that references can be resolved during validation
170 $jsonValidator = new Validator( new Factory($schemaStorage));
172 // JSON must be decoded before it can be validated
173 $jsonToValidateObject = json_decode('{"data":123}');
175 // Do validation (use isValid() and getErrors() to check the result)
176 $jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject);
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.
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 |
195 Please note that using `Constraint::CHECK_MODE_COERCE_TYPES` or `Constraint::CHECK_MODE_APPLY_DEFAULTS`
196 will modify your original data.
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