Completed
Pull Request — master (#51)
by Timothée
03:19
created

JsonSchema   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

2 Methods

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