Test Failed
Pull Request — master (#2)
by Sergey
03:40
created

JsonSchemaValidator::jsonToObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 2
nc 2
nop 1
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
     * @param string $dataName
44
     */
45
    public function validate(stdClass $schema, $data, string $dataName = 'data'): void
46
    {
47
        // Обернем Параметры, для правильной валидации
48
        $dataPlus = (object)[$dataName => $data];
49
50
        // Обернем схему, для правильной валидации
51
        $schemaPlus = (object)[
52
            'type'       => 'object',
53
            'properties' => (object)[
54
                $dataName => $schema,
55
            ],
56
        ];
57
58
        $result = $this->getValidator()->schemaValidation(
59
            $dataPlus,
60
            new Schema($schemaPlus),
61
            10
62
        );
63
64
        if (!$result->isValid()) {
65
            $errors = $result->getErrors();
66
            $errData = [];
67
            foreach ($errors as $error) {
68
                $errData[$error->keyword()] = [
69
                    $error->keywordArgs(),
70
                    $error->dataPointer()
71
                ];
72
            }
73
74
            throw new InvalidParamsException(
75
                'Data validation error', // 'Ошибка валидации данных',
76
                $errData
77
            );
78
        }
79
    }
80
81
    /**
82
     * @return Validator
83
     */
84
    private function getValidator(): Validator
85
    {
86
        return $this->validator;
87
    }
88
}
89