1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Created by PhpStorm. |
5
|
|
|
* Project: json_rpc_server |
6
|
|
|
* User: sv |
7
|
|
|
* Date: 23.03.2020 |
8
|
|
|
* Time: 12:38 |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
declare(strict_types=1); |
12
|
|
|
|
13
|
|
|
namespace Onnov\JsonRpcServer\Validator; |
14
|
|
|
|
15
|
|
|
use Onnov\JsonRpcServer\Traits\JsonHelperTrait; |
16
|
|
|
use Opis\JsonSchema\Validator; |
17
|
|
|
use Opis\JsonSchema\Schema; |
18
|
|
|
use stdClass; |
19
|
|
|
use Onnov\JsonRpcServer\Exception\InvalidParamsException; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Class JsonSchemaValidator |
23
|
|
|
* @package App\Validator\JsonSchema |
24
|
|
|
*/ |
25
|
|
|
class JsonSchemaValidator |
26
|
|
|
{ |
27
|
|
|
use JsonHelperTrait; |
28
|
|
|
|
29
|
|
|
/** @var Validator */ |
30
|
|
|
protected $validator; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* JsonSchemaValidator constructor. |
34
|
|
|
*/ |
35
|
|
|
public function __construct() |
36
|
|
|
{ |
37
|
|
|
$this->validator = new Validator(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param stdClass $schema |
42
|
|
|
* @param stdClass|scalar|null $data |
43
|
|
|
*/ |
44
|
|
|
public function validate(stdClass $schema, $data): void |
45
|
|
|
{ |
46
|
|
|
// Обернем Параметры, для правильной валидации |
47
|
|
|
$dataPlus = (object)['data' => $data]; |
48
|
|
|
|
49
|
|
|
// Обернем схему, для правильной валидации |
50
|
|
|
$schemaPlus = (object)[ |
51
|
|
|
'type' => 'object', |
52
|
|
|
'properties' => (object)[ |
53
|
|
|
'data' => $schema, |
54
|
|
|
], |
55
|
|
|
]; |
56
|
|
|
|
57
|
|
|
$result = $this->getValidator()->schemaValidation( |
58
|
|
|
$dataPlus, |
59
|
|
|
new Schema($schemaPlus), |
60
|
|
|
10 |
61
|
|
|
); |
62
|
|
|
|
63
|
|
|
if (!$result->isValid()) { |
64
|
|
|
$errors = $result->getErrors(); |
65
|
|
|
$errData = []; |
66
|
|
|
foreach ($errors as $error) { |
67
|
|
|
$errData[$error->keyword()] = [ |
68
|
|
|
$error->keywordArgs(), |
69
|
|
|
$error->dataPointer() |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
throw new InvalidParamsException( |
74
|
|
|
'Data validation error', // 'Ошибка валидации данных', |
75
|
|
|
$errData |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return Validator |
82
|
|
|
*/ |
83
|
|
|
private function getValidator(): Validator |
84
|
|
|
{ |
85
|
|
|
return $this->validator; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|