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

JsonIterator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 88.24%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 3
dl 0
loc 85
ccs 30
cts 34
cp 0.8824
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 0 32 7
A count() 0 4 1
A hasNext() 0 8 2
A moveNext() 0 8 2
A key() 0 4 1
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