Passed
Pull Request — master (#2)
by Sergey
03:11
created

JsonSchemaValidator::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 3

Importance

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