1
|
|
|
<?php |
2
|
|
|
namespace LunixRESTBasics\APIRequest\RequestData; |
3
|
|
|
|
4
|
|
|
use LunixRESTBasics\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
|
8 |
|
public function __construct($body) |
19
|
|
|
{ |
20
|
8 |
|
$this->jsonString = $body; |
21
|
8 |
|
$this->parsedData = json_decode($body, true); |
|
|
|
|
22
|
8 |
|
if ($this->parsedData === null) { |
23
|
1 |
|
throw new InvalidRequestDataException('Content not valid JSON'); |
24
|
|
|
} |
25
|
7 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Returns the raw data that the requestData tried to parse |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
1 |
|
public function getRawData(): string |
32
|
|
|
{ |
33
|
1 |
|
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
|
2 |
|
public function get(string $key) |
44
|
|
|
{ |
45
|
2 |
|
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
|
3 |
|
public function has(string $key): bool |
54
|
|
|
{ |
55
|
3 |
|
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
|
1 |
|
public function getAllAsAssociativeArray(): array |
64
|
|
|
{ |
65
|
1 |
|
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..