Passed
Push — master ( 29c8e1...93d991 )
by Sergey
03:05
created

JsonSchemaValidator::getValidator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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