From 8b48f8d74ee361361f80f240c2d341c2df46c941 Mon Sep 17 00:00:00 2001 From: Florent Bruneau Date: Sat, 13 Mar 2010 22:28:38 +0100 Subject: [PATCH] Simplify (and fix) PlFilterIterator. Signed-off-by: Florent Bruneau --- classes/pliteratorutils.php | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/classes/pliteratorutils.php b/classes/pliteratorutils.php index dfa8a36..aff8dc7 100644 --- a/classes/pliteratorutils.php +++ b/classes/pliteratorutils.php @@ -315,45 +315,37 @@ class PlMergeIterator implements PlIterator } -class PlFilterIterator implements PlIterator { +class PlFilterIterator implements PlIterator +{ + private $pos; private $source; private $callback; private $element; - private $start; public function __construct(PlIterator $source, $callback) { - $this->source = $source; + $this->source = $source; $this->callback = $callback; - $this->start = true; - $this->element = null; + $this->pos = 0; + $this->element = $this->fetchNext(); } private function fetchNext() { do { $current = $this->source->next(); - if (!$current) { - $this->element = null; - $this->start = false; - return; - } - $res = call_user_func($this->callback, $current); - if ($res) { - $this->element = $current; - return; + if (is_null($current) || call_user_func($this->callback, $current)) { + return $current; } } while (true); } public function next() { - if ($this->element && $this->start) { - $this->start = false; - } + ++$this->pos; $elt = $this->element; - if ($elt) { - $this->fetchNext(); + if (!is_null($this->element)) { + $this->element = $this->fetchNext(); } return $elt; } @@ -368,12 +360,12 @@ class PlFilterIterator implements PlIterator { public function first() { - return $this->start; + return $this->pos == 1; } public function last() { - return !$this->start && !$this->element; + return is_null($this->element); } } -- 2.1.4