Skip to content

Commit 7514652

Browse files
committed
Add JsonValidationError exception and improve JSON schema error message
1 parent d13dd5f commit 7514652

7 files changed

+396
-26
lines changed

src/Exception/JsonValidationError.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
/**
3+
* This file is part of event-engine/php-json-schema.
4+
* (c) 2018-2019 prooph software GmbH <[email protected]>
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+
declare(strict_types=1);
11+
12+
namespace EventEngine\JsonSchema\Exception;
13+
14+
15+
class JsonValidationError extends InvalidArgumentException
16+
{
17+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
/**
3+
* This file is part of event-engine/php-json-schema.
4+
* (c) 2018-2019 prooph software GmbH <[email protected]>
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+
declare(strict_types=1);
11+
12+
namespace EventEngine\JsonSchema\Exception;
13+
14+
15+
class JustinRainbowJsonValidationError extends JsonValidationError
16+
{
17+
/**
18+
* @var array
19+
*/
20+
private $errors;
21+
22+
public static function withError(string $objectName, array ...$errors): JustinRainbowJsonValidationError
23+
{
24+
$self = new self('Validation of "' . $objectName . '" failed: ');
25+
$self->errors = $errors;
26+
27+
$self->message .= \array_reduce(
28+
$errors,
29+
static function ($message, array $error) use ($self) {
30+
return $message . "\n" . $self->errorMessage($error);
31+
}
32+
);
33+
34+
return $self;
35+
}
36+
37+
public function errors(): array
38+
{
39+
return $this->errors;
40+
}
41+
42+
private function errorMessage(array $error): string
43+
{
44+
$dataPointer = $error['pointer'];
45+
46+
if ($dataPointer === '') {
47+
return \sprintf('[%s] %s', $error['constraint'], $error['message']);
48+
}
49+
50+
return \sprintf('field "%s" [%s] %s',
51+
$error['property'],
52+
$error['constraint'],
53+
$error['message']
54+
);
55+
56+
// return sprintf('field "%s" [%s] %s', $error['constraint'], $error['property'], $error['message']);
57+
}
58+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
/**
3+
* This file is part of event-engine/php-json-schema.
4+
* (c) 2018-2019 prooph software GmbH <[email protected]>
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+
declare(strict_types=1);
11+
12+
namespace EventEngine\JsonSchema\Exception;
13+
14+
15+
use Opis\JsonSchema\ValidationError;
16+
17+
class OpisJsonValidationError extends JsonValidationError
18+
{
19+
/**
20+
* @var ValidationError[]
21+
*/
22+
private $errors;
23+
24+
public static function withError(string $objectName, ValidationError ...$validationErrors): OpisJsonValidationError
25+
{
26+
$self = new self('Validation of "' . $objectName . '" failed: ');
27+
$self->errors = $validationErrors;
28+
29+
foreach ($validationErrors as $error) {
30+
$self->message .= $self->errorMessage($error);
31+
32+
if ($error->subErrorsCount()) {
33+
$self->message .= \array_reduce(
34+
$error->subErrors(),
35+
static function ($message, ValidationError $error) use ($self) {
36+
return $message . "\n" . $self->errorMessage($error);
37+
}
38+
);
39+
}
40+
}
41+
42+
return $self;
43+
}
44+
45+
/**
46+
* @return ValidationError[]
47+
*/
48+
public function errors(): array
49+
{
50+
return $this->errors;
51+
}
52+
53+
private function errorMessage(ValidationError $error): string
54+
{
55+
$dataPointer = $error->dataPointer();
56+
57+
if (count($dataPointer) === 0) {
58+
return \sprintf('[%s] %s', $error->keyword(), \json_encode($error->keywordArgs(), JSON_PRETTY_PRINT));
59+
}
60+
61+
return \sprintf('field "%s" [%s] %s',
62+
implode('.', $dataPointer),
63+
$error->keyword(),
64+
\json_encode($error->keywordArgs(), JSON_PRETTY_PRINT)
65+
);
66+
}
67+
}

src/JustinRainbowJsonSchema.php

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
namespace EventEngine\JsonSchema;
1313

14-
use EventEngine\JsonSchema\Exception\InvalidArgumentException;
14+
use EventEngine\JsonSchema\Exception\JustinRainbowJsonValidationError;
1515
use JsonSchema\Validator;
1616

1717
final class JustinRainbowJsonSchema extends AbstractJsonSchema
@@ -31,16 +31,8 @@ public function assert(string $objectName, array $data, array $jsonSchema)
3131

3232
if (! $this->jsonValidator()->isValid()) {
3333
$errors = $this->jsonValidator()->getErrors();
34-
3534
$this->jsonValidator()->reset();
36-
37-
foreach ($errors as $i => $error) {
38-
$errors[$i] = \sprintf("[%s] %s\n", $error['property'], $error['message']);
39-
}
40-
41-
throw new InvalidArgumentException(
42-
"Validation of $objectName failed: " . \implode("\n", $errors)
43-
);
35+
throw JustinRainbowJsonValidationError::withError($objectName, ...$errors);
4436
}
4537

4638
$this->jsonValidator()->reset();

src/OpisJsonSchema.php

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
namespace EventEngine\JsonSchema;
1313

14-
use EventEngine\JsonSchema\Exception\InvalidArgumentException;
14+
use EventEngine\JsonSchema\Exception\OpisJsonValidationError;
1515
use Opis\JsonSchema\Schema as OpisSchema;
1616
use Opis\JsonSchema\Validator;
1717

@@ -38,21 +38,7 @@ public function assert(string $objectName, array $data, array $jsonSchema)
3838
$result = $this->jsonValidator()->schemaValidation($enforcedObjectData, OpisSchema::fromJsonString(\json_encode($jsonSchema)));
3939

4040
if (! $result->isValid()) {
41-
$errors = [];
42-
43-
foreach ($result->getErrors() as $error) {
44-
$errors[] = \sprintf('[%s] %s', $error->keyword(), \json_encode($error->keywordArgs(), JSON_PRETTY_PRINT));
45-
46-
if ($error->subErrorsCount()) {
47-
foreach ($error->subErrors() as $subError) {
48-
$errors[] = \sprintf("[%s] %s\n", $subError->keyword(), \json_encode($subError->keywordArgs(), JSON_PRETTY_PRINT));
49-
}
50-
}
51-
}
52-
53-
throw new InvalidArgumentException(
54-
"Validation of $objectName failed: " . \implode("\n", $errors)
55-
);
41+
throw OpisJsonValidationError::withError($objectName, ...$result->getErrors());
5642
}
5743
}
5844

tests/JustinRainbowJsonSchemaTest.php

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
<?php
2+
/**
3+
* This file is part of event-engine/php-json-schema.
4+
* (c) 2018-2019 prooph software GmbH <[email protected]>
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+
declare(strict_types=1);
11+
12+
namespace EventEngineTest\JsonSchema;
13+
14+
use EventEngine\JsonSchema\Exception\JsonValidationError;
15+
use EventEngine\JsonSchema\Exception\JustinRainbowJsonValidationError;
16+
use EventEngine\JsonSchema\JustinRainbowJsonSchema;
17+
18+
class JustinRainbowJsonSchemaTest extends BasicTestCase
19+
{
20+
private function schema(): array
21+
{
22+
$schema = <<<'JSON'
23+
{
24+
"$schema": "http://json-schema.org/draft-07/schema#",
25+
"type": "object",
26+
"properties": {
27+
"name": {
28+
"type": "string",
29+
"minLength": 3
30+
},
31+
"hasValue": {"type": "boolean"},
32+
"age": {"type": "number"},
33+
"subObject": {
34+
"type": "object",
35+
"properties": {
36+
"p1": {
37+
"type": "string",
38+
"minLength": 3
39+
},
40+
"p2": {"type": "boolean"}
41+
},
42+
"required": ["p1", "p2"],
43+
"additionalProperties": false
44+
},
45+
"type": {
46+
"enum": ["Foo", "Bar", "Baz"]
47+
}
48+
},
49+
"required": ["name", "hasValue", "age", "type"],
50+
"additionalProperties": false
51+
}
52+
JSON;
53+
return json_decode($schema, true);
54+
}
55+
56+
private function validData(): array
57+
{
58+
return [
59+
'name' => 'Tester',
60+
'hasValue' => true,
61+
'age' => 40,
62+
'type' => 'Bar',
63+
];
64+
}
65+
66+
/**
67+
* @test
68+
*/
69+
public function it_validates_json_schema(): void
70+
{
71+
$data = $this->validData();
72+
73+
$cut = new JustinRainbowJsonSchema();
74+
$cut->assert('myObject', $data, $this->schema());
75+
$this->assertTrue(true);
76+
}
77+
78+
/**
79+
* @test
80+
*/
81+
public function it_throws_json_validation_error_exception(): void
82+
{
83+
$data = $this->validData();
84+
$data['unknown'] = 'set';
85+
86+
$expectedMessage = <<<'Msg'
87+
Validation of "myObject" failed:
88+
[additionalProp] The property unknown is not defined and the definition does not allow additional properties
89+
Msg;
90+
91+
$cut = new JustinRainbowJsonSchema();
92+
try {
93+
$cut->assert('myObject', $data, $this->schema());
94+
} catch (JsonValidationError $e) {
95+
$this->assertSame(400, $e->getCode());
96+
$this->assertStringStartsWith($expectedMessage, $e->getMessage());
97+
}
98+
}
99+
100+
/**
101+
* @test
102+
*/
103+
public function it_throws_justin_rainbow_json_validation_error_exception(): void
104+
{
105+
$data = $this->validData();
106+
$data['subObject']['unknown'] = 'set';
107+
108+
$expectedMessage = <<<'Msg'
109+
Validation of "myObject" failed:
110+
field "subObject.p1" [required] The property p1 is required
111+
field "subObject.p2" [required] The property p2 is required
112+
field "subObject" [additionalProp] The property unknown is not defined and the definition does not allow additional properties
113+
Msg;
114+
115+
116+
$cut = new JustinRainbowJsonSchema();
117+
try {
118+
$cut->assert('myObject', $data, $this->schema());
119+
} catch (JustinRainbowJsonValidationError $e) {
120+
$this->assertSame(400, $e->getCode());
121+
$this->assertCount(3, $e->errors());
122+
$this->assertStringStartsWith($expectedMessage, $e->getMessage());
123+
}
124+
}
125+
}

0 commit comments

Comments
 (0)