Json   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 62
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A fromRawContent() 0 4 1
A read() 0 15 3
A getRawContent() 0 4 1
A encode() 0 8 3
A __toString() 0 4 1
A decode() 0 12 2
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