ObjectIterator.php
2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JsonSchema\Iterator;
/**
* @package JsonSchema\Iterator
*
* @author Joost Nijhuis <jnijhuis81@gmail.com>
*/
class ObjectIterator implements \Iterator, \Countable
{
/** @var object */
private $object;
/** @var int */
private $position = 0;
/** @var array */
private $data = array();
/** @var bool */
private $initialized = false;
/**
* @param object $object
*/
public function __construct($object)
{
$this->object = $object;
}
/**
* {@inheritdoc}
*/
public function current()
{
$this->initialize();
return $this->data[$this->position];
}
/**
* {@inheritdoc}
*/
public function next()
{
$this->initialize();
$this->position++;
}
/**
* {@inheritdoc}
*/
public function key()
{
$this->initialize();
return $this->position;
}
/**
* {@inheritdoc}
*/
public function valid()
{
$this->initialize();
return isset($this->data[$this->position]);
}
/**
* {@inheritdoc}
*/
public function rewind()
{
$this->initialize();
$this->position = 0;
}
/**
* {@inheritdoc}
*/
public function count()
{
$this->initialize();
return count($this->data);
}
/**
* Initializer
*/
private function initialize()
{
if (!$this->initialized) {
$this->data = $this->buildDataFromObject($this->object);
$this->initialized = true;
}
}
/**
* @param object $object
*
* @return array
*/
private function buildDataFromObject($object)
{
$result = array();
$stack = new \SplStack();
$stack->push($object);
while (!$stack->isEmpty()) {
$current = $stack->pop();
if (is_object($current)) {
array_push($result, $current);
}
foreach ($this->getDataFromItem($current) as $propertyName => $propertyValue) {
if (is_object($propertyValue) || is_array($propertyValue)) {
$stack->push($propertyValue);
}
}
}
return $result;
}
/**
* @param object|array $item
*
* @return array
*/
private function getDataFromItem($item)
{
if (!is_object($item) && !is_array($item)) {
return array();
}
return is_object($item) ? get_object_vars($item) : $item;
}
}