Passed
Pull Request — master (#3)
by Joao
04:02
created

JsonDataset::__construct()   C

Complexity

Conditions 8
Paths 14

Size

Total Lines 33
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 14.4058

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 15
cts 28
cp 0.5356
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 27
nc 14
nop 1
crap 14.4058
1
<?php
2
3
namespace ByJG\AnyDataset\Dataset;
4
5
use ByJG\AnyDataset\Exception\DatasetException;
6
7
class JsonDataset
8
{
9
10
    /**
11
     * @var object
12
     */
13
    private $jsonObject;
14
15
    /**
16
     * JsonDataset constructor.
17
     * @param $json
18
     * @throws DatasetException
19
     */
20 8
    public function __construct($json)
21
    {
22 8
        $this->jsonObject = json_decode($json, true);
23
24 8
        $lastError = json_last_error();
25
        switch ($lastError) {
26 8
            case JSON_ERROR_NONE:
27 7
                $lastErrorDesc = 'No errors';
28 7
                break;
29 1
            case JSON_ERROR_DEPTH:
30
                $lastErrorDesc = 'Maximum stack depth exceeded';
31
                break;
32 1
            case JSON_ERROR_STATE_MISMATCH:
33
                $lastErrorDesc = 'Underflow or the modes mismatch';
34
                break;
35 1
            case JSON_ERROR_CTRL_CHAR:
36
                $lastErrorDesc = 'Unexpected control character found';
37
                break;
38 1
            case JSON_ERROR_SYNTAX:
39 1
                $lastErrorDesc = 'Syntax error, malformed JSON';
40 1
                break;
41
            case JSON_ERROR_UTF8:
42
                $lastErrorDesc = 'Malformed UTF-8 characters, possibly incorrectly encoded';
43
                break;
44
            default:
45
                $lastErrorDesc = 'Unknown error';
46
                break;
47
        }
48
49 8
        if ($lastError != JSON_ERROR_NONE) {
50 2
            throw new DatasetException("Invalid JSON string: " . $lastErrorDesc);
51
        }
52 7
    }
53
54
    /**
55
     * @access public
56
     * @param string $path
57
     * @param bool $throwErr
58
     * @return GenericIterator
59
     */
60 7
    public function getIterator($path = "", $throwErr = false)
61
    {
62 7
        $iterator = new JsonIterator($this->jsonObject, $path, $throwErr);
63 6
        return $iterator;
64
    }
65
}
66