Passed
Branch master (d51fdb)
by Joao
05:45 queued 02:33
created

JsonIterator::key()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace ByJG\AnyDataset\Dataset;
4
5
use ByJG\AnyDataset\Exception\IteratorException;
6
use InvalidArgumentException;
7
8
class JsonIterator extends GenericIterator
9
{
10
11
    /**
12
     * @var array
13
     */
14
    private $jsonObject;
15
16
    /**
17
     * Enter description here...
18
     *
19
     * @var int
20
     */
21
    private $current = 0;
22
23
    /**
24
     * JsonIterator constructor.
25
     *
26
     * @param $jsonObject
27
     * @param string $path
28
     * @param bool $throwErr
29
     * @throws \ByJG\AnyDataset\Exception\IteratorException
30
     */
31 7
    public function __construct($jsonObject, $path = "", $throwErr = false)
32
    {
33 7
        if (!is_array($jsonObject)) {
34
            throw new InvalidArgumentException("Invalid JSON object");
35
        }
36
37 7
        if ($path != "") {
38 4
            if ($path[0] == "/") {
39 3
                $path = substr($path, 1);
40
            }
41
42 4
            $pathAr = explode("/", $path);
43
44 4
            $newjsonObject = $jsonObject;
45
46 4
            foreach ($pathAr as $key) {
47 4
                if (array_key_exists($key, $newjsonObject)) {
48 4
                    $newjsonObject = $newjsonObject[$key];
49 2
                } elseif ($throwErr) {
50 1
                    throw new IteratorException("Invalid path '$path' in JSON Object");
51
                } else {
52 1
                    $newjsonObject = array();
53 4
                    break;
54
                }
55
            }
56 3
            $this->jsonObject = $newjsonObject;
57
        } else {
58 3
            $this->jsonObject = $jsonObject;
59
        }
60
61 6
        $this->current = 0;
62 6
    }
63
64 6
    public function count()
65
    {
66 6
        return (count($this->jsonObject));
67
    }
68
69
    /**
70
     * @access public
71
     * @return bool
72
     */
73 5
    public function hasNext()
74
    {
75 5
        if ($this->current < $this->count()) {
76 5
            return true;
77
        }
78
79 4
        return false;
80
    }
81
82
    /**
83
     * @access public
84
     * @return Row
85
     * @throws \ByJG\AnyDataset\Exception\IteratorException
86
     * @throws \ByJG\Serializer\Exception\InvalidArgumentException
87
     */
88 4
    public function moveNext()
89
    {
90 4
        if (!$this->hasNext()) {
91
            throw new IteratorException("No more records. Did you used hasNext() before moveNext()?");
92
        }
93
94 4
        return new Row($this->jsonObject[$this->current++]);
95
    }
96
97
    public function key()
98
    {
99
        return $this->current;
100
    }
101
}
102