Completed
Pull Request — master (#51)
by Timothée
07:46
created

JsonSchema   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 4
c 2
b 1
f 0
lcom 1
cbo 5
dl 0
loc 30
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 17 3
1
<?php
2
3
namespace Rezzza\RestApiBehatExtension\Json;
4
5
use JsonSchema\RefResolver;
6
use JsonSchema\Validator;
7
use JsonSchema\Uri\UriRetriever;
8
use JsonSchema\Uri\UriResolver;
9
10
class JsonSchema
11
{
12
    private $filename;
13
14
    /**
15
     * @param string $filename
16
     */
17
    public function __construct($filename)
18
    {
19
        $this->filename = $filename;
20
    }
21
22
    public function validate(Json $json, Validator $validator)
23
    {
24
        $refResolver = new RefResolver(new UriRetriever, new UriResolver);
25
        $schema = $refResolver->resolve('file://' . realpath($this->filename));
26
27
        $validator->check($json->getRawContent(), $schema);
28
29
        if (!$validator->isValid()) {
30
            $msg = "JSON does not validate. Violations:" . PHP_EOL;
31
            foreach ($validator->getErrors() as $error) {
32
                $msg .= sprintf("  - [%s] %s" . PHP_EOL, $error['property'], $error['message']);
33
            }
34
            throw new \Exception($msg);
35
        }
36
37
        return true;
38
    }
39
}
40