icingaweb2-module-director/library/Director/Data/Db/DbObjectStore.php

65 lines
1.9 KiB
PHP
Raw Normal View History

2021-08-16 11:43:09 +02:00
<?php
namespace Icinga\Module\Director\Data\Db;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Db\Branch\Branch;
use Icinga\Module\Director\Db\Branch\BranchActivity;
use Icinga\Module\Director\Db\Branch\BranchedObject;
2021-08-16 11:43:09 +02:00
/**
* Loader for Icinga/DbObjects
*
* Is aware of branches and prefetching. I would prefer to see a StoreInterface,
* with one of the above wrapping the other. But for now, this helps to clean things
* up
*/
class DbObjectStore
{
/** @var Db */
protected $connection;
/** @var ?Branch */
2021-08-16 11:43:09 +02:00
protected $branch;
public function __construct(Db $connection, Branch $branch = null)
2021-08-16 11:43:09 +02:00
{
$this->connection = $connection;
$this->branch = $branch;
}
public function store(DbObject $object)
2021-08-16 11:43:09 +02:00
{
if ($this->branch && $this->branch->isBranch()) {
$activity = BranchActivity::forDbObject($object, $this->branch);
$this->connection->runFailSafeTransaction(function () use ($activity) {
$activity->store($this->connection);
BranchedObject::withActivity($activity, $this->connection)->store($this->connection);
});
2021-08-16 11:43:09 +02:00
return true;
} else {
return $object->store($this->connection);
}
2021-08-16 11:43:09 +02:00
}
public function delete(DbObject $object)
2021-08-16 11:43:09 +02:00
{
if ($this->branch && $this->branch->isBranch()) {
$activity = BranchActivity::deleteObject($object, $this->branch);
$this->connection->runFailSafeTransaction(function () use ($activity) {
$activity->store($this->connection);
BranchedObject::load(
$this->connection,
$activity->getObjectTable(),
$activity->getObjectUuid(),
$this->branch
)->delete($this->connection);
});
return true;
2021-08-16 11:43:09 +02:00
}
return $object->delete();
2021-08-16 11:43:09 +02:00
}
}