IcingaTemplateRepository: new template lookup...

...strategy, trying to separate concerns
This commit is contained in:
Thomas Gelf 2017-08-11 17:10:31 +02:00
parent 6c4215ee89
commit e683c99a1b
2 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,60 @@
<?php
namespace Icinga\Module\Director\Repository;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\IcingaObject;
use Icinga\Module\Director\Resolver\TemplateTree;
class IcingaTemplateRepository
{
use RepositoryByObjectHelper;
/** @var TemplateTree */
protected $tree;
protected $loadedById = [];
/**
* @return TemplateTree
*/
public function tree()
{
if ($this->tree === null) {
$this->tree = new TemplateTree($this->type, $this->connection);
}
return $this->tree;
}
/**
* @param IcingaObject $object
* @return IcingaObject[]
*/
public function getTemplatesFor(IcingaObject $object)
{
$ids = $this->tree()->listAncestorIdsFor($object);
$templates = [];
foreach ($ids as $id) {
if (! array_key_exists($id, $this->loadedById)) {
// TODO: load only missing ones at once
$this->loadedById[$id] = $object::loadWithAutoIncId(
$id,
$this->connection
);
}
$templates[$id] = $this->loadedById[$id];
}
return $templates;
}
public function persistImportNames()
{
}
public function storeChances(Db $db)
{
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Icinga\Module\Director\Repository;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\IcingaObject;
trait RepositoryByObjectHelper
{
protected $type;
/** @var Db */
protected $connection;
/** @var static[] */
protected static $instances = [];
protected function __construct($type, Db $connection)
{
$this->type = $type;
$this->connection = $connection;
}
/**
* @param $type
* @param Db $connection
* @return static
*/
public static function instanceByType($type, Db $connection)
{
if (!array_key_exists($type, self::$instances)) {
self::$instances[$type] = new static($type, $connection);
}
return self::$instances[$type];
}
/**
* @param IcingaObject $object
* @return static
*/
public static function instanceByObject(IcingaObject $object, Db $connection = null)
{
if (null === $connection) {
$connection = $object->getConnection();
}
if (! $connection) {
var_dump($object->hasBeenLoadedFromDb()); exit;
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
throw new \Exception('SDFA');
}
return static::instanceByType(
$object->getShortTableName(),
$connection
);
}
}