Data\Filter: automagically handle hierarchy

This adds a few more functions assisting filters in replacing
themselves or subnodes. Introducing Filter::chain().
This commit is contained in:
Thomas Gelf 2014-06-20 12:00:29 +02:00
parent 18e49f6b9a
commit 1bfc4058f2
2 changed files with 59 additions and 1 deletions

View File

@ -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)
);
}
/**

View File

@ -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;