Completed
Push — master ( 2516f4...0c284f )
by Dawid
31:42 queued 05:30
created

JsonSchemaValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 59
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 23 3
A mapErrorsToResultViolations() 0 6 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\Service\SchemaValidator;
6
7
use JsonSchema\Validator;
8
9
class JsonSchemaValidator implements SchemaValidatorInterface
10
{
11
    /**
12
     * @var \stdClass
13
     */
14
    protected $schema;
15
16
    /**
17
     * @var Validator
18
     */
19
    protected $validator;
20
21
    /**
22
     * @param \stdClass $schema
23
     * @param Validator $validator
24
     */
25 7
    public function __construct(\stdClass $schema, Validator $validator)
26
    {
27 7
        $this->schema = $schema;
28 7
        $this->validator = $validator;
29 7
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 7
    public function validate(string $jsonString): ValidationResult
35
    {
36 7
        $this->validator->reset();
37
38 7
        $validationResult = new ValidationResult();
39 7
        $decodedJson = json_decode($jsonString);
40
41 7
        if (null === $decodedJson) {
42 2
            $validationResult->addViolation(ValidationViolation::create('Not a JSON or invalid format'));
43
44 2
            return $validationResult;
45
        }
46
47
        try {
48 5
            $this->validator->check($decodedJson, $this->schema);
49 1
        } catch (\Exception $e) {
50 1
            $validationResult->addViolation(ValidationViolation::create(sprintf('Validator check exception: "%s"', $e->getMessage())));
51
        }
52
53 5
        $this->mapErrorsToResultViolations($validationResult);
54
55 5
        return $validationResult;
56
    }
57
58
    /**
59
     * @param ValidationResult $validationResult
60
     */
61 5
    protected function mapErrorsToResultViolations(ValidationResult $validationResult): void
62
    {
63 5
        foreach ($this->validator->getErrors() as $error) {
64 3
            $validationResult->addViolation(ValidationViolation::create($error['message'], $error['property']));
65
        }
66 5
    }
67
}
68