Completed
Pull Request — master (#61)
by Michal
02:15
created

JsonSchemaValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 13
cts 13
cp 1
rs 9.6
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
namespace Tomaj\NetteApi\Validation;
4
5
use JsonSchema\Validator;
6
use Tomaj\NetteApi\ValidationResult\ValidationResult;
7
use Tomaj\NetteApi\ValidationResult\ValidationResultInterface;
8
9
class JsonSchemaValidator
10
{
11
    /**
12
     * @param mixed $data
13
     * @param string $schema
14
     * @return ValidationResultInterface
15
     */
16 12
    public function validate($data, string $schema): ValidationResultInterface
17
    {
18 12
        $schemaValidator = new Validator();
19 12
        $schemaValidator->validate($data, json_decode($schema));
20
21 12
        if ($schemaValidator->isValid()) {
22 6
            return new ValidationResult(ValidationResult::STATUS_OK);
23
        }
24
25 6
        $errors = [];
26 6
        foreach ($schemaValidator->getErrors() as $error) {
27 6
            $errorMessage = '';
28 6
            if ($error['property']) {
29 3
                $errorMessage .= '[Property ' . $error['property'] . '] ';
30
            }
31 6
            $errorMessage .= $error['message'];
32 6
            $errors[] = $errorMessage;
33
        }
34 6
        return new ValidationResult(ValidationResult::STATUS_ERROR, $errors);
35
    }
36
}
37