Passed
Push — master ( 4ee9ec...849354 )
by San
04:18 queued 03:37
created

JsonSchema::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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