1 | <?php |
||
28 | class JsonValidator |
||
29 | { |
||
30 | /** |
||
31 | * The schema used for validating schemas. |
||
32 | * |
||
33 | * @var object|null |
||
34 | */ |
||
35 | private $metaSchema; |
||
36 | |||
37 | /** |
||
38 | * Validator instance used for validation. |
||
39 | * |
||
40 | * @var Validator |
||
41 | */ |
||
42 | private $validator; |
||
43 | |||
44 | /** |
||
45 | * JsonValidator constructor. |
||
46 | * |
||
47 | * @param Validator|null $validator JsonSchema\Validator instance to use. |
||
48 | */ |
||
49 | public function __construct(Validator $validator = null) |
||
50 | { |
||
51 | 23 | $this->validator = $validator ?: new Validator(); |
|
52 | } |
||
53 | 23 | ||
54 | 12 | /** |
|
55 | 8 | * Validates JSON data against a schema. |
|
56 | 21 | * |
|
57 | * The schema may be passed as file path or as object returned from |
||
58 | * `json_decode($schemaFile)`. |
||
59 | 21 | * |
|
60 | * @param mixed $data The decoded JSON data. |
||
61 | * @param string|object $schema The schema file or object. |
||
62 | 21 | * |
|
63 | 21 | * @return string[] The errors found during validation. Returns an empty |
|
64 | 1 | * array if no errors were found. |
|
65 | 1 | * |
|
66 | 1 | * @throws InvalidSchemaException If the schema is invalid. |
|
67 | 1 | */ |
|
68 | public function validate($data, $schema) |
||
69 | { |
||
70 | 21 | if (is_string($schema)) { |
|
71 | $schema = $this->loadSchema($schema); |
||
72 | 21 | } else { |
|
73 | 14 | $this->assertSchemaValid($schema); |
|
74 | } |
||
75 | 14 | ||
76 | 14 | $this->validator->reset(); |
|
77 | 14 | ||
78 | 14 | try { |
|
79 | 14 | $this->validator->check($data, $schema); |
|
80 | } catch (InvalidArgumentException $e) { |
||
81 | 21 | throw new InvalidSchemaException(sprintf( |
|
82 | 'The schema is invalid: %s', |
||
83 | $e->getMessage() |
||
84 | 21 | ), 0, $e); |
|
85 | } |
||
86 | 21 | ||
87 | $errors = array(); |
||
88 | |||
89 | 21 | if (!$this->validator->isValid()) { |
|
90 | 21 | $errors = (array) $this->validator->getErrors(); |
|
91 | |||
92 | 21 | foreach ($errors as $key => $error) { |
|
93 | 21 | $prefix = $error['property'] ? $error['property'].': ' : ''; |
|
94 | $errors[$key] = $prefix.$error['message']; |
||
95 | } |
||
96 | 21 | } |
|
97 | |||
98 | 21 | return $errors; |
|
99 | 4 | } |
|
100 | 4 | ||
101 | 4 | private function assertSchemaValid($schema) |
|
131 | 2 | ||
132 | 2 | private function loadSchema($file) |
|
133 | 2 | { |
|
155 | } |
||
156 |