aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorIvan Enderlin <ivan.enderlin@hoa-project.net>2013-05-13 19:04:18 +0200
committerIvan Enderlin <ivan.enderlin@hoa-project.net>2013-05-13 19:04:18 +0200
commit59dcff7f331a7338644cf9a8965d2a934a38661e (patch)
tree393daf129d134823cc6f7e66fa45c339816dea46
parent353151e49393f8d0772183f9415bb697edf2486b (diff)
downloadIterator-59dcff7f331a7338644cf9a8965d2a934a38661e.zip
Iterator-59dcff7f331a7338644cf9a8965d2a934a38661e.tar.gz
Iterator-59dcff7f331a7338644cf9a8965d2a934a38661e.tar.bz2
A multiple iterator can have default values.
When the multiple iterator has the MIT_NEED_ANY flags, and when one of the attached iterators has reached its end, the return value is NULL. We change this behavior by allowing a different default value. Example with no default value: $it = new \Hoa\Iterator\Multiple( \MultipleIterator::MIT_NEED_ANY | \MultipleIterator::MIT_KEYS_ASSOC ); $it->attachIterator(new \ArrayIterator(['a', 'b', 'c']), 'foo'); $it->attachIterator(new \ArrayIterator(['x']), 'bar'); foreach($it as $value) echo $value['foo'], ' => ', $value['bar'], "\n"; /** * Will output: * a => x * b => * c => */ Example with 42 as a default value: $it->attachIterator(new \ArrayIterator(['a', 'b', 'c']), 'foo', 42); $it->attachIterator(new \ArrayIterator(['x']), 'bar', 42); foreach($it as $value) echo $value['foo'], ' => ', $value['bar'], "\n"; /** * Will output: * a => x * b => 42 * c => 42 */ It is clearly useful when one of the iterators returns an array, used directly in a loop. To avoid a “NULL pointer exception”, we can specify an empty array as a default value.
-rw-r--r--Multiple.php53
1 files changed, 52 insertions, 1 deletions
diff --git a/Multiple.php b/Multiple.php
index 7da4cb0..06a2697 100644
--- a/Multiple.php
+++ b/Multiple.php
@@ -46,6 +46,57 @@ namespace Hoa\Iterator {
* @license New BSD License
*/
-class Multiple extends \MultipleIterator { }
+class Multiple extends \MultipleIterator {
+
+ /**
+ * Default value for each $infos.
+ *
+ * @var \Hoa\Iterator\Multiple array
+ */
+ protected $_infos = array();
+
+
+
+ /**
+ * Attach iterator informations.
+ * Add the $default argument that will be use when the iterator has reached
+ * its end.
+ *
+ * @access public
+ * @param \Iterator $iterator Iterator.
+ * @param string $infos Informations to attach.
+ * @param mixed $default Default value.
+ * @return void
+ */
+ public function attachIterator ( \Iterator $iterator, $infos = null,
+ $default = null ) {
+
+ $out = parent::attachIterator($iterator, $infos);
+
+ if(null === $infos)
+ $this->_infos[] = $default;
+ else
+ $this->_infos[$infos] = $default;
+
+ return $out;
+ }
+
+ /**
+ * Get the registered iterator instances.
+ *
+ * @access public
+ * @return array
+ */
+ public function current ( ) {
+
+ $out = parent::current();
+
+ foreach($out as $key => &$value)
+ if(null === $value)
+ $value = $this->_infos[$key];
+
+ return $out;
+ }
+}
}