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

JSONRequestData   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 56
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A getRawData() 0 3 1
A get() 0 3 1
A has() 0 3 1
A getAllAsAssociativeArray() 0 3 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