Completed
Push — master ( 281c81...f6b491 )
by Sebastian
04:07
created

JsonBody::getEncodedString()   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
rs 10
c 0
b 0
f 0
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 \Kartenmacherei\RestFramework\JsonArray|JsonObject
39
     */
40
    public function query(string $selector)
41
    {
42
        return $this->json->query($selector);
43
    }
44
45
    /**
46
     * @return JsonObject
47
     */
48
    public function getJson(): JsonObject
49
    {
50
        return $this->json;
51
    }
52
53
    /**
54
     * @return string
55
     */
56
    public function getEncodedString(): string
57
    {
58
        return $this->jsonString;
59
    }
60
61
    /**
62
     * @param string $jsonString
63
     * @return JsonObject
64
     * @throws EnsureException
65
     */
66
    private function decode(string $jsonString): JsonObject
67
    {
68
        $decoded = json_decode($jsonString, false);
69
        if (json_last_error() !== JSON_ERROR_NONE) {
70
            throw new EnsureException(sprintf('JSON body could not be decoded: %s', json_last_error_msg()));
71
        }
72
        return new JsonObject($decoded);
73
    }
74
75
}
76