<?php
namespace ApplicationBundle\TimeService;
use CompanyGroupBundle\Entity\CompanyGroup;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class TenantDbConfigResolver
{
private $cache;
private $companyGroupEntityManager;
public function __construct(CacheInterface $cache, EntityManagerInterface $companyGroupEntityManager)
{
$this->cache = $cache;
$this->companyGroupEntityManager = $companyGroupEntityManager;
}
public function resolveByAppId($appID): array
{
$appID = (int) $appID;
if ($appID <= 0) {
throw new \RuntimeException('Missing appID for tenant DB resolution.');
}
$cacheKey = $this->getCacheKey($appID);
return $this->cache->get($cacheKey, function (ItemInterface $item) use ($appID) {
$item->expiresAfter(900);
/** @var CompanyGroup|null $companyGroup */
$companyGroup = $this->companyGroupEntityManager
->getRepository(CompanyGroup::class)
->findOneBy([
'appId' => $appID,
]);
if (!$companyGroup) {
throw new \RuntimeException('CompanyGroup not found for appID.');
}
return [
'dbName' => $companyGroup->getDbName(),
'dbUser' => $companyGroup->getDbUser(),
'dbPassword' => $companyGroup->getDbPass(),
'dbHost' => $companyGroup->getDbHost(),
];
});
}
public function invalidateByAppId($appID): void
{
$this->cache->delete($this->getCacheKey($appID));
}
private function getCacheKey($appID): string
{
return 'tenant_db_config_app_' . preg_replace('/[^a-zA-Z0-9_:-]/', '_', (string) $appID);
}
}