From 0e95424b8ceb913f81b0672f0171d2fc0e32bbe2 Mon Sep 17 00:00:00 2001 From: Florent Bruneau Date: Tue, 28 Sep 2010 10:11:52 +0200 Subject: [PATCH] Add PlIteratorUtils::foreachIterator() to build a PHP's Iterator from a PlIterator. Signed-off-by: Florent Bruneau --- classes/pliteratorutils.php | 50 +++++++++++++++++++++++++++++++++++++++++++++ ut/spliteratortest.php | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 ut/spliteratortest.php diff --git a/classes/pliteratorutils.php b/classes/pliteratorutils.php index c9bf046..875aac7 100644 --- a/classes/pliteratorutils.php +++ b/classes/pliteratorutils.php @@ -135,6 +135,13 @@ class PlIteratorUtils $callback = new _GetObjectPropertyCallback($property); return array($callback, 'get'); } + + /** Returns a wrapper around the PlIterator suitable for foreach() iterations + */ + public static function foreachIterator(PlIterator $iterator) + { + return new SPLIterator($iterator); + } } /** Empty iterator @@ -803,5 +810,48 @@ class _GetObjectPropertyCallback } } +// Wrapper class to build a SPL iterator from a PlIterator +class SPLIterator implements Iterator +{ + private $it; + private $pos; + private $value; + + public function __construct(PlIterator $it) + { + $this->it = $it; + $this->pos = 0; + $this->value = $this->it->next(); + } + + public function rewind() + { + if ($this->pos != 0) { + throw new Exception("Rewind not supported on this iterator"); + } + } + + public function current() + { + return $this->value; + } + + public function key() + { + return $this->pos; + } + + public function next() + { + ++$this->pos; + $this->value = $this->it->next(); + } + + public function valid() + { + return !!$this->value; + } +} + // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: ?> diff --git a/ut/spliteratortest.php b/ut/spliteratortest.php new file mode 100644 index 0000000..87f9c89 --- /dev/null +++ b/ut/spliteratortest.php @@ -0,0 +1,42 @@ + $value) { + $this->assertSame($values[$key], $value); + $get[] = $value; + } + $this->assertSame($values, $get); + } +} + +// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: +?> -- 2.1.4