1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace OpenStack\Common\JsonSchema; |
4
|
|
|
|
5
|
|
|
use JsonSchema\Validator; |
6
|
|
|
|
7
|
|
|
class Schema |
8
|
|
|
{ |
9
|
|
|
private $body; |
10
|
|
|
private $validator; |
11
|
|
|
|
12
|
4 |
|
public function __construct($body, Validator $validator = null) |
13
|
|
|
{ |
14
|
4 |
|
$this->body = (object) $body; |
15
|
4 |
|
$this->validator = $validator ?: new Validator(); |
16
|
4 |
|
} |
17
|
|
|
|
18
|
1 |
|
public function getPropertyPaths() |
19
|
|
|
{ |
20
|
1 |
|
$paths = []; |
21
|
|
|
|
22
|
1 |
|
foreach ($this->body->properties as $propertyName => $property) { |
23
|
1 |
|
$paths[] = sprintf("/%s", $propertyName); |
24
|
1 |
|
} |
25
|
|
|
|
26
|
1 |
|
return $paths; |
27
|
|
|
} |
28
|
|
|
|
29
|
2 |
|
public function normalizeObject($subject, array $aliases) |
30
|
|
|
{ |
31
|
2 |
|
$out = new \stdClass; |
32
|
|
|
|
33
|
2 |
|
foreach ($this->body->properties as $propertyName => $property) { |
34
|
2 |
|
$name = isset($aliases[$propertyName]) ? $aliases[$propertyName] : $propertyName; |
35
|
2 |
|
if (isset($property->readOnly) && $property->readOnly === true) { |
36
|
2 |
|
continue; |
37
|
2 |
|
} elseif (property_exists($subject, $name)) { |
38
|
2 |
|
$out->$propertyName = $subject->$name; |
39
|
2 |
|
} elseif (property_exists($subject, $propertyName)) { |
40
|
1 |
|
$out->$propertyName = $subject->$propertyName; |
41
|
1 |
|
} |
42
|
2 |
|
} |
43
|
|
|
|
44
|
2 |
|
return $out; |
45
|
|
|
} |
46
|
|
|
|
47
|
2 |
|
public function validate($data) |
48
|
|
|
{ |
49
|
2 |
|
$this->validator->check($data, $this->body); |
50
|
2 |
|
} |
51
|
|
|
|
52
|
2 |
|
public function isValid() |
53
|
|
|
{ |
54
|
2 |
|
return $this->validator->isValid(); |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
public function getErrors() |
58
|
|
|
{ |
59
|
3 |
|
return $this->validator->getErrors(); |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
public function getErrorString() |
63
|
|
|
{ |
64
|
2 |
|
$msg = "Provided values do not validate. Errors:\n"; |
65
|
|
|
|
66
|
2 |
|
foreach ($this->getErrors() as $error) { |
67
|
2 |
|
$msg .= sprintf("[%s] %s\n", $error['property'], $error['message']); |
68
|
2 |
|
} |
69
|
|
|
|
70
|
2 |
|
return $msg; |
71
|
|
|
} |
72
|
|
|
} |