JsonSchemaValidator::getData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php declare(strict_types = 1);
2
3
namespace RamosHenrique\JsonSchemaValidator;
4
5
use stdClass;
6
7
use Swaggest\JsonSchema\Schema as BaseSchema;
8
9
class JsonSchemaValidator
10
{
11
    protected $jsonSchema;
12
    protected $rawData;
13
14
    public function setSchema(string $filePath): void
15
    {
16
        if (!file_exists($filePath)) {
17
            throw new JsonSchemaValidatorException(JsonSchemaValidatorException::FILE_DOESNT_EXIST);
18
        }
19
20
        $this->jsonSchema = (string) file_get_contents($filePath);
21
    }
22
23
    public function getSchema(): stdClass
24
    {
25
        return json_decode($this->jsonSchema);
26
    }
27
28
    public function setData(string $data): void
29
    {
30
        $this->rawData = $data;
31
    }
32
33
    public function getData(): stdClass
34
    {
35
        return json_decode($this->rawData);
36
    }
37
38
    public function validate(): bool
39
    {
40
        $schema = $this->getSchema();
41
        $schemaDecode = json_last_error();
42
        $data = $this->getData();
43
44
        $dataDecode = json_last_error();
45
46
        if ($schemaDecode != JSON_ERROR_NONE ||
47
            $dataDecode != JSON_ERROR_NONE
48
        ) {
49
            throw new JsonSchemaValidatorException(JsonSchemaValidatorException::WASNT_POSSIBLE_DECODE_PARAMETERS);
50
        }
51
52
        $schema = BaseSchema::import($schema);
53
        $schema->in($data);
54
55
        return true;
56
    }
57
}
58