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

JsonSchema::hasUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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