Completed
Push — master ( fc96a9...ebe14f )
by
unknown
04:28
created

JsonBody::getJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace Kartenmacherei\RestFramework\Request\Body;
3
4
use Kartenmacherei\RestFramework\EnsureException;
5
use Kartenmacherei\RestFramework\JsonObject;
6
7
class JsonBody extends Body
8
{
9
    /**
10
     * @var JsonObject
11
     */
12
    private $json = [];
13
14
    /**
15
     * @var string
16
     */
17
    private $jsonString = '';
18
19
    /**
20
     * @param string $jsonString
21
     */
22
    public function __construct($jsonString)
23
    {
24
        $this->json = $this->decode($jsonString);
25
        $this->jsonString = $jsonString;
26
    }
27
28
    /**
29
     * @return bool
30
     */
31
    public function isJson(): bool
32
    {
33
        return true;
34
    }
35
36
    /**
37
     * @param string $selector
38
     * @return bool
39
     */
40
    public function has(string $selector): bool
41
    {
42
        return $this->json->has($selector);
43
    }
44
45
    /**
46
     * @param string $selector
47
     * @return \Kartenmacherei\RestFramework\JsonArray|JsonObject
48
     */
49
    public function query(string $selector)
50
    {
51
        return $this->json->query($selector);
52
    }
53
54
    /**
55
     * @return JsonObject
56
     */
57
    public function getJson(): JsonObject
58
    {
59
        return $this->json;
60
    }
61
62
    /**
63
     * @return string
64
     */
65
    public function getEncodedString(): string
66
    {
67
        return $this->jsonString;
68
    }
69
70
    /**
71
     * @param string $jsonString
72
     * @return JsonObject
73
     * @throws EnsureException
74
     */
75
    private function decode(string $jsonString): JsonObject
76
    {
77
        $decoded = json_decode($jsonString, false);
78
        if (json_last_error() !== JSON_ERROR_NONE) {
79
            throw new EnsureException(sprintf('JSON body could not be decoded: %s', json_last_error_msg()));
80
        }
81
        return new JsonObject($decoded);
82
    }
83
84
}
85