Json::encode()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Rezzza\RestApiBehatExtension\Json;
4
5
use Symfony\Component\PropertyAccess\PropertyAccessor;
6
7
class Json
8
{
9
    private $content;
10
11
    public function __construct($content, $encodedAsString = true)
12
    {
13
        $this->content = true === $encodedAsString ? $this->decode((string) $content) : $content;
14
    }
15
16
    public static function fromRawContent($content)
17
    {
18
        return new static($content, false);
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 getRawContent()
38
    {
39
        return $this->content;
40
    }
41
42
    public function encode($pretty = true)
43
    {
44
        if (true === $pretty && defined('JSON_PRETTY_PRINT')) {
45
            return json_encode($this->content, JSON_PRETTY_PRINT);
46
        }
47
48
        return json_encode($this->content);
49
    }
50
51
    public function __toString()
52
    {
53
        return $this->encode(false);
54
    }
55
56
    private function decode($content)
57
    {
58
        $result = json_decode($content);
59
60
        if (json_last_error() !== JSON_ERROR_NONE) {
61
            throw new \Exception(
62
                sprintf('The string "%s" is not valid json', $content)
63
            );
64
        }
65
66
        return $result;
67
    }
68
}
69