IcingaObjectGroups: provide autocreate and ignore...

...failure options for objects assigned to missing groups by name
This commit is contained in:
Thomas Gelf 2016-02-19 15:36:56 +01:00
parent 2ff3764818
commit f2f748738e

View File

@ -124,12 +124,12 @@ class IcingaObjectGroups implements Iterator, Countable, IcingaConfigRenderer
$this->idx = array_keys($this->groups); $this->idx = array_keys($this->groups);
} }
public function add($group) public function add($group, $onError = 'fail')
{ {
// TODO: only one query when adding array // TODO: only one query when adding array
if (is_array($group)) { if (is_array($group)) {
foreach ($group as $g) { foreach ($group as $g) {
$this->add($g); $this->add($g, $onError);
} }
return $this; return $this;
} }
@ -139,25 +139,47 @@ class IcingaObjectGroups implements Iterator, Countable, IcingaConfigRenderer
} }
$class = $this->getGroupClass(); $class = $this->getGroupClass();
$connection = $this->object->getConnection();
if ($group instanceof $class) { if ($group instanceof $class) {
$this->groups[$group->object_name] = $group; $this->groups[$group->object_name] = $group;
} elseif (is_string($group)) { } elseif (is_string($group)) {
$connection = $this->object->getConnection();
// TODO: fix this, prefetch or whatever - this is expensive
$query = $this->object->getDb()->select()->from( $query = $this->object->getDb()->select()->from(
$this->getGroupTableName() $this->getGroupTableName()
)->where('object_name = ?', $group); )->where('object_name = ?', $group);
$groups = $class::loadAll($connection, $query, 'object_name'); $groups = $class::loadAll($connection, $query, 'object_name');
}
if (! array_key_exists($group, $groups)) { if (! array_key_exists($group, $groups)) {
switch ($onError) {
case 'autocreate':
$groups[$group] = $class::create(array(
'object_type' => 'object',
'object_name' => $group
));
$groups[$group]->store($connection);
// TODO
case 'fail':
throw new ProgrammingError(
'The group "%s" doesn\'t exists.',
$group
);
break;
case 'ignore':
return $this;
}
}
} else {
throw new ProgrammingError( throw new ProgrammingError(
'The group "%s" doesn\'t exists.', 'Invalid group object: %s',
$group var_export($group, 1)
); );
} }
$this->groups[$group] = $groups[$group]; $this->groups[$group] = $groups[$group];
$this->modified = true; $this->modified = true;
$this->refreshIndex(); $this->refreshIndex();