File tree Expand file tree Collapse file tree 4 files changed +71
-3
lines changed
Expand file tree Collapse file tree 4 files changed +71
-3
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+ // The JSON we will validate. Notice that one of the array keys is not a string,
3+ // and the "colour" property is misspelled.
4+ use Gt \Json \JsonObjectBuilder ;
5+ use Gt \Json \Schema \ValidationError ;
6+ use Gt \Json \Schema \Validator ;
7+
8+ require __DIR__ . "/../vendor/autoload.php " ;
9+
10+ $ jsonString = <<<JSON
11+ {
12+ "name": "Cody",
13+ "colr": "orange",
14+ "food": [
15+ "Biscuits",
16+ "Mushrooms",
17+ 12345
18+ ]
19+ }
20+ JSON ;
21+
22+ $ schemaString = <<<JSON
23+ {
24+ " \$schema": "https://json-schema.org/draft/2020-12/schema",
25+ "title": "Simple object schema",
26+ "type": "object",
27+ "properties": {
28+ "name": {
29+ "type": "string",
30+ "minLength": 1
31+ },
32+ "colour": {
33+ "type": "string"
34+ },
35+ "food": {
36+ "type": "array",
37+ "items": {
38+ "type": "string"
39+ }
40+ }
41+ },
42+ "required": [
43+ "name",
44+ "colour",
45+ "food"
46+ ],
47+ "additionalProperties": false
48+ }
49+ JSON ;
50+
51+ $ builder = new JsonObjectBuilder ();
52+
53+ $ schema = $ builder ->fromJsonString ($ schemaString );
54+ $ json = $ builder ->fromJsonString ($ jsonString );
55+
56+ $ validator = new Validator ($ schema );
57+ $ result = $ validator ->validate ($ json );
58+
59+ if ($ result instanceof ValidationError) {
60+ echo "Error validating JSON! " , PHP_EOL ;
61+
62+ foreach ($ result ->getErrorList () as $ propertyName => $ errorString ) {
63+ echo "$ propertyName: $ errorString " , PHP_EOL ;
64+ }
65+ }
66+ else {
67+ echo "Everything is OK! " , PHP_EOL ;
68+ }
Original file line number Diff line number Diff line change @@ -98,7 +98,7 @@ public function fromFile(string $filePath):JsonObject {
9898 throw new FileNotFoundException ($ filePath );
9999 }
100100
101- return self ::fromJsonString (file_get_contents ($ filePath ));
101+ return self ::fromJsonString (file_get_contents ($ filePath ) ?: "" );
102102 }
103103
104104}
Original file line number Diff line number Diff line change 1010class ValidationError extends ValidationResult implements JsonSerializable {
1111 /** @param array<string> $errorList */
1212 public function __construct (
13- private JsonKvpObject $ schema ,
13+ private JsonObject $ schema ,
1414 private array $ errorList ,
1515 ) {}
1616
Original file line number Diff line number Diff line change 88
99class Validator {
1010 public function __construct (
11- private ?JsonKvpObject $ schema = null ,
11+ private ?JsonObject $ schema = null ,
1212 ) {}
1313
1414 public function validate (JsonObject $ json ):ValidationResult {
You can’t perform that action at this time.
0 commit comments