From 1bfc4058f2b8440ffa30c95fb9a1e0e4f088caad Mon Sep 17 00:00:00 2001 From: Thomas Gelf Date: Fri, 20 Jun 2014 12:00:29 +0200 Subject: [PATCH] Data\Filter: automagically handle hierarchy This adds a few more functions assisting filters in replacing themselves or subnodes. Introducing Filter::chain(). --- library/Icinga/Data/Filter/Filter.php | 36 +++++++++++++++++++++- library/Icinga/Data/Filter/FilterChain.php | 24 +++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/library/Icinga/Data/Filter/Filter.php b/library/Icinga/Data/Filter/Filter.php index 2162716f5..67f14199f 100644 --- a/library/Icinga/Data/Filter/Filter.php +++ b/library/Icinga/Data/Filter/Filter.php @@ -42,6 +42,24 @@ abstract class Filter return $this->id; } + public function isRootNode() + { + return false === strpos($this->id, '-'); + } + + public function getParentId() + { + if ($self->isRootNode()) { + throw new ProgrammingError('Filter root nodes have no parent'); + } + return substr($this->id, 0, strrpos($this->id, '-')); + } + + public function getParent() + { + return $this->getById($this->getParentId()); + } + public function hasId($id) { if ($id === $this->getId()) { @@ -126,7 +144,23 @@ abstract class Filter $args = $args[0]; } } - return new FilterNot($args); + if (count($args) > 1) { + return new FilterNot(array(new FilterAnd($args))); + } else { + return new FilterNot($args); + } + } + + public static function chain($operator, $filters = array()) + { + switch ($operator) { + case 'AND': return self::matchAll($filters); + case 'OR' : return self::matchAny($filters); + case 'NOT': return self::not($filters); + } + throw new ProgrammingError( + sprintf('"%s" is not a valid filter chain operator', $operator) + ); } /** diff --git a/library/Icinga/Data/Filter/FilterChain.php b/library/Icinga/Data/Filter/FilterChain.php index bcb4d2b56..47224a91b 100644 --- a/library/Icinga/Data/Filter/FilterChain.php +++ b/library/Icinga/Data/Filter/FilterChain.php @@ -2,6 +2,8 @@ namespace Icinga\Data\Filter; +use Icinga\Exception\ProgrammingError; + /** * FilterChain * @@ -57,6 +59,28 @@ abstract class FilterChain extends Filter return $this; } + public function replaceById($id, $filter) + { + $found = false; + foreach ($this->filters as $k => $child) { + if ($child->getId() == $id) { + $this->filters[$k] = $filter; + $found = true; + break; + } + if ($child->hasId($id)) { + $child->replaceById($id, $filter); + $found = true; + break; + } + } + if (! $found) { + throw new ProgrammingError('You tried to replace an unexistant child filter'); + } + $this->refreshChildIds(); + return $this; + } + protected function refreshChildIds() { $i = 0;