JsonSchema::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Behatch\Json;
4
5
use JsonSchema\SchemaStorage;
6
use JsonSchema\Validator;
7
8
class JsonSchema extends Json
9
{
10
    private $uri;
11
12
    public function __construct($content, $uri = null)
13
    {
14
        $this->uri = $uri;
15
16
        parent::__construct($content);
17
    }
18
19
    public function resolve(SchemaStorage $resolver)
20
    {
21
        if (!$this->hasUri()) {
22
            return $this;
23
        }
24
25
        $this->content = $resolver->resolveRef($this->uri);
26
27
        return $this;
28
    }
29
30
    public function validate(Json $json, Validator $validator)
31
    {
32
        $validator->check($json->getContent(), $this->getContent());
33
34
        if (!$validator->isValid()) {
35
            $msg = "JSON does not validate. Violations:".PHP_EOL;
36
            foreach ($validator->getErrors() as $error) {
37
                $msg .= sprintf("  - [%s] %s".PHP_EOL, $error['property'], $error['message']);
38
            }
39
            throw new \Exception($msg);
40
        }
41
42
        return true;
43
    }
44
45
    private function hasUri()
46
    {
47
        return null !== $this->uri;
48
    }
49
}
50