Completed
Branch 3.0.0 (a8a3e4)
by Joao
03:24
created

JsonIterator::moveNext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 2.0625
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 7
    public function __construct($jsonObject, $path = "", $throwErr = false)
24
    {
25 7
        if (!is_array($jsonObject)) {
26
            throw new InvalidArgumentException("Invalid JSON object");
27
        }
28
29 7
        if ($path != "") {
30 4
            if ($path[0] == "/") {
31 3
                $path = substr($path, 1);
32 3
            }
33
34 4
            $pathAr = explode("/", $path);
35
36 4
            $newjsonObject = $jsonObject;
37
38 4
            foreach ($pathAr as $key) {
39 4
                if (array_key_exists($key, $newjsonObject)) {
40 4
                    $newjsonObject = $newjsonObject[$key];
41 4
                } elseif ($throwErr) {
42 1
                    throw new IteratorException("Invalid path '$path' in JSON Object");
43
                } else {
44 1
                    $newjsonObject = array();
45 1
                    break;
46
                }
47 4
            }
48 3
            $this->jsonObject = $newjsonObject;
49 3
        } else {
50 3
            $this->jsonObject = $jsonObject;
51
        }
52
53 6
        $this->current = 0;
54 6
    }
55
56 6
    public function count()
57
    {
58 6
        return (count($this->jsonObject));
59
    }
60
61
    /**
62
     * @access public
63
     * @return bool
64
     */
65 5
    public function hasNext()
66
    {
67 5
        if ($this->current < $this->count()) {
68 5
            return true;
69
        }
70
71 4
        return false;
72
    }
73
74
    /**
75
     * @access public
76
     * @return SingleRow
77
     * @throws IteratorException
78
     */
79 4
    public function moveNext()
80
    {
81 4
        if (!$this->hasNext()) {
82
            throw new IteratorException("No more records. Did you used hasNext() before moveNext()?");
83
        }
84
85 4
        return new SingleRow($this->jsonObject[$this->current++]);
86
    }
87
88
    public function key()
89
    {
90
        return $this->current;
91
    }
92
}
93