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
|
|
|
|