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