|
1
|
|
|
<?php |
|
2
|
|
|
namespace LunixREST\Request\RequestData; |
|
3
|
|
|
|
|
4
|
|
|
use LunixREST\Request\BodyParser\Exceptions\InvalidRequestDataException; |
|
5
|
|
|
|
|
6
|
|
|
class JSONRequestData implements RequestData { |
|
7
|
|
|
|
|
8
|
|
|
protected $jsonString; |
|
9
|
|
|
|
|
10
|
|
|
protected $parsedData = []; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* JSONRequestData constructor. |
|
14
|
|
|
* @param $body |
|
15
|
|
|
* @throws InvalidRequestDataException |
|
16
|
|
|
*/ |
|
17
|
|
|
public function __construct($body) { |
|
18
|
|
|
$this->jsonString = $body; |
|
19
|
|
|
$this->parsedData = json_decode($body, true); |
|
20
|
|
|
if($this->parsedData === null) { |
|
21
|
|
|
throw new InvalidRequestDataException('Content not valid JSON'); |
|
22
|
|
|
} |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Returns the raw data that the requestData tried to parse |
|
27
|
|
|
* @return string |
|
28
|
|
|
*/ |
|
29
|
|
|
public function getRawData(): string { |
|
30
|
|
|
return $this->jsonString; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Attempts to get a specific key from the parsed data. Returns NULL if non-existent key (use has($key) if |
|
35
|
|
|
* there is a difference between a null value and a missing value) |
|
36
|
|
|
* WARNING: Parsed data is not sanitized, and should be treated as regular user data |
|
37
|
|
|
* @param string $key |
|
38
|
|
|
* @return mixed |
|
39
|
|
|
*/ |
|
40
|
|
|
public function get(string $key) { |
|
41
|
|
|
return $this->parsedData[$key] ?? null; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Attempts to find a specific key in the parsed data. Returns true if found else false |
|
46
|
|
|
* @param string $key |
|
47
|
|
|
* @return mixed |
|
48
|
|
|
*/ |
|
49
|
|
|
public function has(string $key): bool { |
|
50
|
|
|
return isset($this->parsedData[$key]); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Gets all parsed data as an associative array |
|
55
|
|
|
* WARNING: Parsed data is not sanitized, and should be treated as regular user data |
|
56
|
|
|
* @return array |
|
57
|
|
|
*/ |
|
58
|
|
|
public function getAllAsAssociativeArray(): array { |
|
59
|
|
|
return $this->parsedData; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|