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\Errors\ErrorFormatter; |
17
|
|
|
use Opis\JsonSchema\Validator; |
18
|
|
|
use stdClass; |
19
|
|
|
use Onnov\JsonRpcServer\Exception\InvalidParamsException; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Class JsonSchemaValidator |
23
|
|
|
* |
24
|
|
|
* @package App\Validator\JsonSchema |
25
|
|
|
*/ |
26
|
|
|
class JsonSchemaValidator |
27
|
|
|
{ |
28
|
|
|
use JsonHelperTrait; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var Validator |
32
|
|
|
*/ |
33
|
|
|
protected $validator; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* JsonSchemaValidator constructor. |
37
|
|
|
*/ |
38
|
9 |
|
public function __construct() |
39
|
|
|
{ |
40
|
9 |
|
$this->validator = new Validator(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param stdClass $schema |
45
|
|
|
* @param stdClass|mixed[]|scalar|null $data |
46
|
|
|
* @param string $dataName |
47
|
|
|
*/ |
48
|
8 |
|
public function validate(stdClass $schema, $data, string $dataName = 'data'): void |
49
|
|
|
{ |
50
|
8 |
|
if (is_array($data)) { |
51
|
|
|
$data = $this->arrayToObject($data); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// Обернем Параметры, для правильной валидации |
55
|
8 |
|
$dataPlus = (object)[$dataName => $data]; |
56
|
|
|
|
57
|
|
|
// Обернем схему, для правильной валидации |
58
|
8 |
|
$schemaPlus = (object)[ |
59
|
8 |
|
'type' => 'object', |
60
|
8 |
|
'properties' => (object)[ |
61
|
8 |
|
$dataName => $schema, |
62
|
8 |
|
], |
63
|
8 |
|
]; |
64
|
|
|
|
65
|
8 |
|
$result = $this |
66
|
8 |
|
->getValidator() |
67
|
8 |
|
->setMaxErrors(10) |
68
|
8 |
|
->validate( |
69
|
8 |
|
$dataPlus, |
70
|
8 |
|
$schemaPlus |
71
|
8 |
|
); |
72
|
|
|
|
73
|
8 |
|
if (!$result->isValid()) { |
74
|
2 |
|
throw new InvalidParamsException( |
75
|
2 |
|
'', //'Data validation error', // 'Ошибка валидации данных', |
76
|
2 |
|
0, |
77
|
2 |
|
null, |
78
|
2 |
|
(new ErrorFormatter())->formatFlat($result->error()) |
79
|
2 |
|
); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @return Validator |
85
|
|
|
*/ |
86
|
8 |
|
private function getValidator(): Validator |
87
|
|
|
{ |
88
|
8 |
|
return $this->validator; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|