Hoa central
CartesianProduct.php
Go to the documentation of this file.
1 <?php
2 
38 
39 use Hoa\Iterator;
40 
55 class CartesianProduct implements Iterator
56 {
62  protected $_sets = [];
63 
69  protected $_max = 0;
70 
76  protected $_key = 0;
77 
83  protected $_current = null;
84 
90  protected $_break = true;
91 
92 
93 
101  public function __construct($set)
102  {
103  foreach (func_get_args() as $s) {
104  if (is_array($s)) {
105  $s = new Iterator\Map($s);
106  } else {
107  $s = new Iterator\IteratorIterator($s);
108  }
109 
110  $this->_sets[] = $s;
111  }
112 
113  $this->_max = count($this->_sets) - 1;
114  $this->_break = empty($this->_sets);
115 
116  return;
117  }
118 
124  public function current()
125  {
126  return $this->_current;
127  }
128 
134  protected function _current()
135  {
136  $this->_current = [];
137 
138  foreach ($this->_sets as $set) {
139  $this->_current[] = $set->current();
140  }
141 
142  return;
143  }
144 
150  public function key()
151  {
152  return $this->_key;
153  }
154 
160  public function next()
161  {
162  for ($i = 0; $i <= $this->_max; ++$i) {
163  $this->_sets[$i]->next();
164 
165  if (false !== $this->_sets[$i]->valid()) {
166  break;
167  }
168 
169  $this->_sets[$i]->rewind();
170 
171  if ($i === $this->_max) {
172  $this->_break = true;
173 
174  break;
175  }
176  }
177 
178  ++$this->_key;
179  $this->_current();
180 
181  return $this->current();
182  }
183 
189  public function rewind()
190  {
191  $this->_break = empty($this->_sets);
192  $this->_key = 0;
193 
194  foreach ($this->_sets as $set) {
195  $set->rewind();
196  }
197 
198  $this->_current();
199 
200  return $this->current();
201  }
202 
209  public function valid()
210  {
211  return false === $this->_break;
212  }
213 }