Completed
Push — master ( aa8b89...6eacd0 )
by John
01:54
created

JSONRequestData::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
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);
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode($body, true) of type * is incompatible with the declared type array of property $parsedData.

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..

Loading history...
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