diff --git a/src/Filter/Chain.php b/src/Filter/Chain.php index a64f095..ac4df41 100644 --- a/src/Filter/Chain.php +++ b/src/Filter/Chain.php @@ -15,6 +15,9 @@ abstract class Chain implements Rule, MetaDataProvider, IteratorAggregate, Count /** @var Rule[] */ protected $rules = []; + /** @var ArrayIterator */ + protected $iterator; + /** * Create a new Chain * @@ -46,9 +49,13 @@ public function __clone() * * @return ArrayIterator */ - public function getIterator(): Traversable + public function getIterator(bool $fromCache = false): Traversable { - return new ArrayIterator($this->rules); + if (! $this->iterator || ! $this->iterator->valid() || ! $fromCache) { + $this->iterator = new ArrayIterator($this->rules); + } + + return $this->iterator; } /** @@ -61,6 +68,9 @@ public function getIterator(): Traversable public function add(Rule $rule) { $this->rules[] = $rule; + if ($rule instanceof Condition) { + $rule->setChain($this); + } return $this; } diff --git a/src/Filter/Condition.php b/src/Filter/Condition.php index cc35610..72826be 100644 --- a/src/Filter/Condition.php +++ b/src/Filter/Condition.php @@ -2,6 +2,8 @@ namespace ipl\Stdlib\Filter; +use ipl\Stdlib\Filter; + abstract class Condition implements Rule, MetaDataProvider { use MetaData; @@ -12,6 +14,9 @@ abstract class Condition implements Rule, MetaDataProvider /** @var mixed */ protected $value; + /** @var Chain */ + protected $chain; + /** * Create a new Condition * @@ -81,4 +86,22 @@ public function getValue() { return $this->value; } + + /** + * @param Filter\Chain $chain + */ + public function setChain(Filter\Chain $chain) + { + $this->chain = $chain; + + return $this; + } + + /** + * @return Filter\Chain + */ + public function getChain() + { + return $this->chain; + } }