JsonSchema::validate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
rs 9.4285
cc 3
eloc 10
nc 3
nop 3
1
<?php
2
3
namespace Rezzza\RestApiBehatExtension\Json;
4
5
use JsonSchema\SchemaStorage;
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, SchemaStorage $schemaStorage)
21
    {
22
        $schema = $schemaStorage->resolveRef('file://' . realpath($this->filename));
23
        $data = $json->getRawContent();
24
25
        $validator->check($data, $schema);
26
27
        if (!$validator->isValid()) {
28
            $msg = "JSON does not validate. Violations:" . PHP_EOL;
29
            foreach ($validator->getErrors() as $error) {
30
                $msg .= sprintf("  - [%s] %s" . PHP_EOL, $error['property'], $error['message']);
31
            }
32
            throw new \Exception($msg);
33
        }
34
35
        return true;
36
    }
37
}
38