Passed
Push — master ( 0ce3b5...f76703 )
by Dawid
03:41
created

JsonSchemaValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 80%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 49
ccs 16
cts 20
cp 0.8
rs 10

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;
6
7
use JsonSchema\Validator;
8
9
class JsonSchemaValidator
10
{
11
    /**
12
     * @var \stdClass
13
     */
14
    protected $schema;
15
16
    /**
17
     * @var Validator
18
     */
19
    protected $validator;
20
21 1
    public function __construct(\stdClass $schema, Validator $validator)
22
    {
23 1
        $this->schema = $schema;
24 1
        $this->validator = $validator;
25 1
    }
26
27 1
    public function validate(string $jsonString): ValidationResult
28
    {
29 1
        $this->validator->reset();
30
31 1
        $validationResult = new ValidationResult();
32 1
        $decodedJson = json_decode($jsonString);
33
34 1
        if (null === $decodedJson) {
35
            $validationResult->addViolation(ValidationViolation::create('Not a JSON or invalid format'));
36
37
            return $validationResult;
38
        }
39
40
        try {
41 1
            $this->validator->check($decodedJson, $this->schema);
42
        } catch (\Exception $e) {
43
            $validationResult->addViolation(ValidationViolation::create($e->getMessage()));
44
        }
45
46 1
        $this->mapErrorsToResultViolations($this->validator, $validationResult);
47
48 1
        return $validationResult;
49
    }
50
51 1
    protected function mapErrorsToResultViolations(Validator $validator, ValidationResult $validationResult): void
52
    {
53 1
        foreach ($validator->getErrors() as $error) {
54 1
            $validationResult->addViolation(ValidationViolation::create($error['message'], $error['property']));
55
        }
56 1
    }
57
}
58