Completed
Pull Request — master (#2)
by Sergey
03:37
created

JsonSchemaValidator::arrayToObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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