From cf6daf157a135fb95feb570197e8c6d8c78b482d Mon Sep 17 00:00:00 2001 From: Yonas Habteab Date: Thu, 8 Sep 2022 13:38:12 +0200 Subject: [PATCH 1/2] Condition: Allow to track parent chain --- src/Filter/Condition.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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; + } } From bcb4d20aed0c8712cf64817987806e770b41a0c7 Mon Sep 17 00:00:00 2001 From: Yonas Habteab Date: Thu, 8 Sep 2022 13:38:35 +0200 Subject: [PATCH 2/2] Chain: Allow to use cached iterator This PR tries not to create a new iterator, as long it is not explicitly requested to and the current iterator is still valid. --- src/Filter/Chain.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) 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; }