Completed
Push — master ( e55977...d99d38 )
by Sebastian
02:38
created

JsonBody   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isJson() 0 4 1
A query() 0 4 1
A getJson() 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
     * @param string $jsonString
16
     */
17
    public function __construct($jsonString)
18
    {
19
        $this->json = $this->decode($jsonString);
20
    }
21
22
    /**
23
     * @return bool
24
     */
25
    public function isJson(): bool
26
    {
27
        return true;
28
    }
29
30
    /**
31
     * @param string $selector
32
     * @return \Kartenmacherei\RestFramework\JsonArray|JsonObject
33
     */
34
    public function query(string $selector)
35
    {
36
        return $this->json->query($selector);
37
    }
38
39
    /**
40
     * @return JsonObject
41
     */
42
    public function getJson(): JsonObject
43
    {
44
        return $this->json;
45
    }
46
47
    /**
48
     * @param string $jsonString
49
     * @return JsonObject
50
     * @throws EnsureException
51
     */
52
    private function decode(string $jsonString): JsonObject
53
    {
54
        $decoded = json_decode($jsonString, false);
55
        if (json_last_error() !== JSON_ERROR_NONE) {
56
            throw new EnsureException(sprintf('JSON body could not be decoded: %s', json_last_error_msg()));
57
        }
58
        return new JsonObject($decoded);
59
    }
60
61
}
62