<?php
namespace ProjectBiz\DatabaseBundle\Database;
use ProjectBiz\DatabaseBundle\Service\RepositoryConfigurationManager;
use ProjectBiz\UserBundle\Service\SecurityContextWrapper;
use Symfony\Contracts\Translation\TranslatorInterface;
class TableHelper implements TableHelperInterface
{
public $securityContext;
protected $configManager;
protected $databaseSchemaCache;
protected $translator;
protected $tableAndViewList;
protected $cachedViewList;
protected $cachedTableLists = [];
protected $cachedInfo = [];
public function __construct(
SecurityContextWrapper $securityContext,
RepositoryConfigurationManager $configManager,
DatabaseSchemaCache $databaseSchemaCache,
TranslatorInterface $translator
) {
$this->securityContext = $securityContext;
$this->configManager = $configManager;
$this->databaseSchemaCache = $databaseSchemaCache;
$this->translator = $translator;
}
/**
* @inheritdoc
*/
public function getTableInfo($tablename)
{
if (!isset($this->cachedInfo[$tablename])) {
if ($this->isView($tablename)) {
$this->cachedInfo[$tablename] = new ViewInfo(
$tablename,
$this->databaseSchemaCache,
$this,
$this->translator
);
} else {
$this->cachedInfo[$tablename] = new TableInfo(
$this->getTableDescriptor($tablename),
$this->databaseSchemaCache,
$this,
$this->translator
);
}
}
return $this->cachedInfo[$tablename];
}
/**
* @inheritdoc
*/
public function isView($tablename)
{
return in_array($tablename, $this->getViews());
}
/**
* @return array List of views in database
*/
protected function getViews()
{
return $this->databaseSchemaCache->getViews();
}
/**
* @param $tablename
*
* @return TableDescriptor
*/
protected function getTableDescriptor($tablename)
{
$tableDesciptor = $this->configManager->lookupDescriptor($tablename);
if (!$tableDesciptor) {
$tableDesciptor = new TableDescriptor($tablename, $tablename);
}
return $tableDesciptor;
}
/**
* @inheritdoc
*/
public function getTables($withViews = true, $withSynTables = true)
{
// Determine index for cached list:
// 0 = only tables
// 1 = tables and syn tables
// 2 = tables and views
// 3 = tables, syn tables and views
$index = 0 | ($withSynTables?1:0) | ($withViews?2:0);
if (!isset($this->cachedTableLists[$index])) {
// 1. Collect Database-Tables starting with prefix
$tableList = $this->databaseSchemaCache->getTables();
// 2. merge the synthetic tables found in RepositoryConfigurationManager
if ($withSynTables) {
$tableList = array_merge($tableList, $this->configManager->getTables());
}
// 3. Merge the views
if ($withViews) {
$tableList = array_merge($tableList, $this->getViews());
}
$this->cachedTableLists[$index] = $tableList;
}
return $this->cachedTableLists[$index];
}
/**
* @inheritdoc
*/
public function getColumnNameSubString($column)
{
return substr($column, strpos($column, '_') + 1);
}
}