Json::read()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 4
nop 2
1
<?php
2
3
namespace Behatch\Json;
4
5
use Symfony\Component\PropertyAccess\PropertyAccessor;
6
7
class Json
8
{
9
    protected $content;
10
11
    public function __construct($content)
12
    {
13
        $this->content = $this->decode((string) $content);
14
    }
15
16
    public function getContent()
17
    {
18
        return $this->content;
19
    }
20
21
    public function read($expression, PropertyAccessor $accessor)
22
    {
23
        if (is_array($this->content)) {
24
            $expression =  preg_replace('/^root/', '', $expression);
25
        } else {
26
            $expression =  preg_replace('/^root./', '', $expression);
27
        }
28
29
        // If root asked, we return the entire content
30
        if (strlen(trim($expression)) <= 0) {
31
            return $this->content;
32
        }
33
34
        return $accessor->getValue($this->content, $expression);
35
    }
36
37
    public function encode($pretty = true)
38
    {
39
        $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
40
41
        if (true === $pretty && defined('JSON_PRETTY_PRINT')) {
42
            $flags |= JSON_PRETTY_PRINT;
43
        }
44
45
        return json_encode($this->content, $flags);
46
    }
47
48
    public function __toString()
49
    {
50
        return $this->encode(false);
51
    }
52
53
    private function decode($content)
54
    {
55
        $result = json_decode($content);
56
57
        if (json_last_error() !== JSON_ERROR_NONE) {
58
            throw new \Exception("The string '$content' is not valid json");
59
        }
60
61
        return $result;
62
    }
63
}
64