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