Skip to content

Commit 0bbaac8

Browse files
KristopherWindsorbighappyface
authored andcommitted
Update README.md to include a second usage example (With inline refs) (#313)
* Update README.md to include a second usage example (With inline references) * clarity and formatting improvements for recent changes to README.md
1 parent a918d3b commit 0bbaac8

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ See [json-schema](http://json-schema.org/) for more details.
2323

2424
## Usage
2525

26+
### Basic usage
27+
2628
```php
2729
<?php
2830

@@ -68,6 +70,59 @@ is_int($request->refundAmount); // true
6870

6971
Note that the ```CHECK_MODE_COERCE``` flag will only take effect when an object is passed into the ```check``` method.
7072

73+
### With inline references
74+
75+
```php
76+
<?php
77+
78+
use JsonSchema\SchemaStorage;
79+
use JsonSchema\Validator;
80+
81+
$jsonSchema = <<<'JSON'
82+
{
83+
"type": "object",
84+
"properties": {
85+
"data": {
86+
"oneOf": [
87+
{ "$ref": "#/definitions/integerData" },
88+
{ "$ref": "#/definitions/stringData" }
89+
]
90+
}
91+
},
92+
"required": ["data"],
93+
"definitions": {
94+
"integerData" : {
95+
"type": "integer",
96+
"minimum" : 0
97+
},
98+
"stringData" : {
99+
"type": "string"
100+
}
101+
}
102+
}
103+
JSON;
104+
105+
// Schema must be decoded before it can be used for validation
106+
$jsonSchemaObject = json_decode($jsonSchema);
107+
108+
// The SchemaStorage can resolve references, loading additional schemas from file as needed, etc.
109+
$schemaStorage = new SchemaStorage();
110+
111+
// This does two things:
112+
// 1) Mutates $jsonSchemaObject to normalize the references (to file://mySchema#/definitions/integerData, etc)
113+
// 2) Tells $schemaStorage that references to file://mySchema... should be resolved by looking in $jsonSchemaObject
114+
$schemaStorage->addSchema('file://mySchema', $jsonSchemaObject);
115+
116+
// Provide $schemaStorage to the Validator so that references can be resolved during validation
117+
$jsonValidator = new Validator(Validator::CHECK_MODE_NORMAL, $schemaStorage);
118+
119+
// JSON must be decoded before it can be validated
120+
$jsonToValidateObject = json_decode('{"data":123}');
121+
122+
// Do validation (use isValid() and getErrors() to check the result)
123+
$jsonValidator->check($jsonToValidateObject, $jsonSchemaObject);
124+
```
125+
71126
## Running the tests
72127

73128
$ vendor/bin/phpunit

0 commit comments

Comments
 (0)