Skip to content

Commit 7eb38e2

Browse files
eraydbighappyface
authored andcommitted
Option to throw exceptions when an error is encountered (#354)
* Add option to throw an exception on validation errors * Update README * Changes API references to use the new Validator::validate() entry point * Adds section describing available config options
1 parent 9b6ebfe commit 7eb38e2

File tree

5 files changed

+106
-11
lines changed

5 files changed

+106
-11
lines changed

README.md

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ $data = json_decode(file_get_contents('data.json'));
3333

3434
// Validate
3535
$validator = new JsonSchema\Validator;
36-
$validator->check($data, (object)['$ref' => 'file://' . realpath('schema.json')]);
36+
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);
3737

3838
if ($validator->isValid()) {
3939
echo "The supplied JSON validates against the schema.\n";
@@ -63,22 +63,31 @@ $request = (object)[
6363
'refundAmount'=>"17"
6464
];
6565

66-
$validator->coerce($request, (object) [
66+
$validator->validate(
67+
$request, (object) [
6768
"type"=>"object",
68-
"properties"=>(object)[
69-
"processRefund"=>(object)[
70-
"type"=>"boolean"
71-
],
72-
"refundAmount"=>(object)[
73-
"type"=>"number"
69+
"properties"=>(object)[
70+
"processRefund"=>(object)[
71+
"type"=>"boolean"
72+
],
73+
"refundAmount"=>(object)[
74+
"type"=>"number"
75+
]
7476
]
75-
]
76-
]); // validates!
77+
],
78+
Constraint::CHECK_MODE_COERCE_TYPES
79+
); // validates!
7780

7881
is_bool($request->processRefund); // true
7982
is_int($request->refundAmount); // true
8083
```
8184

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+
8291
### With inline references
8392

8493
```php
@@ -130,9 +139,23 @@ $jsonValidator = new Validator( new Factory($schemaStorage));
130139
$jsonToValidateObject = json_decode('{"data":123}');
131140

132141
// Do validation (use isValid() and getErrors() to check the result)
133-
$jsonValidator->check($jsonToValidateObject, $jsonSchemaObject);
142+
$jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject);
134143
```
135144

145+
### Configuration Options
146+
A number of flags are available to alter the behavior of the validator. These can be passed as the
147+
third argument to `Validator::validate()`, or can be provided as the third argument to
148+
`Factory::__construct()` if you wish to persist them across multiple `validate()` calls.
149+
150+
| Flag | Description |
151+
|------|-------------|
152+
| `Constraint::CHECK_MODE_NORMAL` | Validate in 'normal' mode - this is the default |
153+
| `Constraint::CHECK_MODE_TYPE_CAST` | Enable fuzzy type checking for associative arrays and objects |
154+
| `Constraint::CHECK_MODE_COERCE_TYPES` | Convert data types to match the schema where possible |
155+
| `Constraint::CHECK_MODE_EXCEPTIONS` | Throw an exception immediately if validation fails |
156+
157+
Please note that using `Constraint::CHECK_MODE_COERCE_TYPES` will modify your original data.
158+
136159
## Running the tests
137160

138161
```bash

src/JsonSchema/Constraints/BaseConstraint.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
namespace JsonSchema\Constraints;
1111

1212
use JsonSchema\Entity\JsonPointer;
13+
use JsonSchema\Exception\ValidationException;
1314

1415
/**
1516
* A more basic constraint definition - used for the public
@@ -47,6 +48,10 @@ public function addError(JsonPointer $path = null, $message, $constraint = '', a
4748
'constraint' => $constraint,
4849
);
4950

51+
if ($this->factory->getConfig(Constraint::CHECK_MODE_EXCEPTIONS)) {
52+
throw new ValidationException(sprintf("Error validating %s: %s", $error['pointer'], $error['message']));
53+
}
54+
5055
if (is_array($more) && count($more) > 0)
5156
{
5257
$error += $more;

src/JsonSchema/Constraints/Constraint.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ abstract class Constraint extends BaseConstraint implements ConstraintInterface
2929
const CHECK_MODE_TYPE_CAST = 0x00000002;
3030
const CHECK_MODE_COERCE_TYPES = 0x00000004;
3131
const CHECK_MODE_APPLY_DEFAULTS = 0x00000008;
32+
const CHECK_MODE_EXCEPTIONS = 0x00000010;
3233

3334
/**
3435
* Bubble down the path
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the JsonSchema package.
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace JsonSchema\Exception;
11+
12+
class ValidationException extends RuntimeException
13+
{
14+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the JsonSchema package.
5+
*
6+
* For the full copyright and license information, please view the LICENSE
7+
* file that was distributed with this source code.
8+
*/
9+
10+
namespace JsonSchema\Tests\Constraints;
11+
12+
use JsonSchema\Validator;
13+
use JsonSchema\Constraints\Constraint;
14+
use JsonSchema\Exception\ValidationException;
15+
16+
class ValidationExceptionTest extends \PHPUnit_Framework_TestCase
17+
{
18+
public function testValidationException()
19+
{
20+
$exception = new ValidationException();
21+
$this->assertInstanceOf('\JsonSchema\Exception\ValidationException', $exception);
22+
23+
$checkValue = json_decode('{"propertyOne": "thisIsNotAnObject"}');
24+
$schema = json_decode('{
25+
"type": "object",
26+
"additionalProperties": false,
27+
"properties": {
28+
"propertyOne": {
29+
"type": "object"
30+
}
31+
}
32+
}');
33+
34+
$validator = new Validator();
35+
36+
try {
37+
$validator->validate($checkValue, $schema, Constraint::CHECK_MODE_EXCEPTIONS);
38+
} catch (\Exception $e) {
39+
$exception = $e;
40+
}
41+
42+
$this->assertEquals(
43+
'Error validating /propertyOne: String value found, but an object is required',
44+
$exception->getMessage()
45+
);
46+
47+
48+
$this->setExpectedException('JsonSchema\Exception\ValidationException');
49+
throw $exception;
50+
51+
}
52+
}

0 commit comments

Comments
 (0)