forked from martin-helmich/phpunit-json-assert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonValueMatchesSchema.php
More file actions
85 lines (73 loc) · 1.88 KB
/
JsonValueMatchesSchema.php
File metadata and controls
85 lines (73 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace Sid\JsonAssert\Constraint;
use JsonSchema\Validator;
use PHPUnit\Framework\Constraint\Constraint;
use stdClass;
/**
* A constraint for asserting that a JSON document matches a schema
*
* @package Sid\JsonAssert
* @subpackage Constraint
*/
class JsonValueMatchesSchema extends Constraint
{
/**
* @var array|stdClass
*/
private $schema;
/**
* JsonValueMatchesSchema constructor.
*
* @param array|stdClass $schema The JSON schema
*/
public function __construct($schema)
{
$this->schema = $this->forceToObject($schema);
}
/**
* VERY dirty hack to force a JSON document into an object.
*
* Yell if you can think of something better.
*
* @param array|stdClass $jsonDocument
* @return stdClass
*/
private function forceToObject($jsonDocument)
{
if (is_string($jsonDocument)) {
return json_decode($jsonDocument);
}
return json_decode(json_encode($jsonDocument));
}
/**
* @inheritdoc
*/
protected function matches($other): bool
{
$other = $this->forceToObject($other);
$validator = new Validator();
$validator->check($other, $this->schema);
return $validator->isValid();
}
/**
* @inheritdoc
*/
protected function additionalFailureDescription($other): string
{
$other = $this->forceToObject($other);
$validator = new Validator();
$validator->check($other, $this->schema);
return implode("\n", array_map(function ($error) {
return sprintf("[%s] %s", $error['property'], $error['message']);
}, $validator->getErrors()));
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString(): string
{
return 'matches JSON schema';
}
}