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

JsonBody   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 69
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A isJson() 0 4 1
A query() 0 4 1
A getJson() 0 4 1
A getEncodedString() 0 4 1
A decode() 0 8 2
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