Completed
Push — master ( 158f00...4ee9ec )
by San
06:17 queued 02:55
created

Json   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 56
rs 10
c 2
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getContent() 0 4 1
A read() 0 15 3
A encode() 0 9 3
A __toString() 0 4 1
A decode() 0 10 2
1
<?php
2
3
namespace Behatch\Json;
4
5
use Symfony\Component\PropertyAccess\PropertyAccessor;
6
7
class Json
8
{
9
    private $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
        if (true === $pretty && defined('JSON_PRETTY_PRINT')) {
40
            // Cannot test this part JSON_PRETTY_PRINT is only 5.4
41
            return json_encode($this->content, JSON_PRETTY_PRINT);
42
        }
43
44
        return json_encode($this->content);
45
    }
46
47
    public function __toString()
48
    {
49
        return $this->encode(false);
50
    }
51
52
    private function decode($content)
53
    {
54
        $result = json_decode($content);
55
56
        if (json_last_error() !== JSON_ERROR_NONE) {
57
            throw new \Exception("The string '$content' is not valid json");
58
        }
59
60
        return $result;
61
    }
62
}
63