src/ApplicationBundle/TimeService/TenantDbConfigResolver.php line 50

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\TimeService;
  3. use CompanyGroupBundle\Entity\CompanyGroup;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Contracts\Cache\CacheInterface;
  6. use Symfony\Contracts\Cache\ItemInterface;
  7. class TenantDbConfigResolver
  8. {
  9.     private $cache;
  10.     private $companyGroupEntityManager;
  11.     public function __construct(CacheInterface $cacheEntityManagerInterface $companyGroupEntityManager)
  12.     {
  13.         $this->cache $cache;
  14.         $this->companyGroupEntityManager $companyGroupEntityManager;
  15.     }
  16.     public function resolveByAppId($appID): array
  17.     {
  18.         $appID = (int) $appID;
  19.         if ($appID <= 0) {
  20.             throw new \RuntimeException('Missing appID for tenant DB resolution.');
  21.         }
  22.         $cacheKey $this->getCacheKey($appID);
  23.         return $this->cache->get($cacheKey, function (ItemInterface $item) use ($appID) {
  24.             $item->expiresAfter(900);
  25.             /** @var CompanyGroup|null $companyGroup */
  26.             $companyGroup $this->companyGroupEntityManager
  27.                 ->getRepository(CompanyGroup::class)
  28.                 ->findOneBy([
  29.                     'appId' => $appID,
  30.                 ]);
  31.             if (!$companyGroup) {
  32.                 throw new \RuntimeException('CompanyGroup not found for appID.');
  33.             }
  34.             return [
  35.                 'dbName' => $companyGroup->getDbName(),
  36.                 'dbUser' => $companyGroup->getDbUser(),
  37.                 'dbPassword' => $companyGroup->getDbPass(),
  38.                 'dbHost' => $companyGroup->getDbHost(),
  39.             ];
  40.         });
  41.     }
  42.     public function invalidateByAppId($appID): void
  43.     {
  44.         $this->cache->delete($this->getCacheKey($appID));
  45.     }
  46.     private function getCacheKey($appID): string
  47.     {
  48.         return 'tenant_db_config_app_' preg_replace('/[^a-zA-Z0-9_:-]/''_', (string) $appID);
  49.     }
  50. }