Completed
Push — master ( e6719d...13ae3c )
by John
01:53
created

JSONRequestData::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
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