|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the JVal 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 JVal; |
|
11
|
|
|
|
|
12
|
|
|
use Closure; |
|
13
|
|
|
use stdClass; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* JSON Schema validation entry point. |
|
17
|
|
|
*/ |
|
18
|
|
|
class Validator |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var Walker |
|
22
|
|
|
*/ |
|
23
|
|
|
private $walker; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Builds a default validator instance. Accepts an optional pre-fetch |
|
27
|
|
|
* hook. |
|
28
|
|
|
* |
|
29
|
|
|
* @see Resolver::setPreFetchHook |
|
30
|
|
|
* |
|
31
|
|
|
* @param Closure $preFetchHook |
|
32
|
|
|
* |
|
33
|
|
|
* @return Validator |
|
34
|
|
|
*/ |
|
35
|
302 |
|
public static function buildDefault(Closure $preFetchHook = null) |
|
36
|
|
|
{ |
|
37
|
302 |
|
$registry = new Registry(); |
|
38
|
302 |
|
$resolver = new Resolver(); |
|
39
|
|
|
|
|
40
|
302 |
|
if ($preFetchHook) { |
|
41
|
302 |
|
$resolver->setPreFetchHook($preFetchHook); |
|
42
|
302 |
|
} |
|
43
|
|
|
|
|
44
|
302 |
|
$walker = new Walker($registry, $resolver); |
|
45
|
|
|
|
|
46
|
302 |
|
return new self($walker); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Constructor. |
|
51
|
|
|
* |
|
52
|
|
|
* @param Walker $walker |
|
53
|
|
|
*/ |
|
54
|
302 |
|
public function __construct(Walker $walker) |
|
55
|
|
|
{ |
|
56
|
302 |
|
$this->walker = $walker; |
|
57
|
302 |
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Validates an instance against a given schema and returns a list |
|
61
|
|
|
* of violations, if any. If the schema contains relative remote |
|
62
|
|
|
* references, its (absolute) URI must be passed as argument. |
|
63
|
|
|
* |
|
64
|
|
|
* @param mixed $instance |
|
65
|
|
|
* @param stdClass $schema |
|
66
|
|
|
* @param string $schemaUri |
|
67
|
|
|
* |
|
68
|
|
|
* @return array |
|
69
|
|
|
*/ |
|
70
|
302 |
|
public function validate($instance, stdClass $schema, $schemaUri = '') |
|
71
|
|
|
{ |
|
72
|
302 |
|
$parseContext = new Context(); |
|
73
|
302 |
|
$constraintContext = new Context(); |
|
74
|
|
|
|
|
75
|
|
|
// todo: keep ref of already resolved/parsed schemas |
|
76
|
|
|
|
|
77
|
302 |
|
$schema = $this->walker->resolveReferences($schema, new Uri($schemaUri)); |
|
78
|
302 |
|
$schema = $this->walker->parseSchema($schema, $parseContext); |
|
79
|
302 |
|
$this->walker->applyConstraints($instance, $schema, $constraintContext); |
|
80
|
|
|
|
|
81
|
302 |
|
return $constraintContext->getViolations(); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|