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

JsonSchema::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
dl 0
loc 16
rs 9.4285
c 2
b 1
f 0
cc 3
eloc 9
nc 3
nop 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