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

JsonSchemaValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 28
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 20 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