src/Services/SwitchTenantManager.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\Services;
  3. use App\Entity\Main\Tenant;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. class SwitchTenantManager
  7. {
  8.     private $event;
  9.     private $request;
  10.     public function __construct(ManagerRegistry $eventRequestStack $request)
  11.     {
  12.         $this->request $request;
  13.         $this->event $event;
  14.         $this->defaultManager $this->event->getManager();
  15.     }
  16.     public function reconnect()
  17.     {
  18.         $server $this->request->getCurrentRequest()->server->get('HTTP_HOST');
  19.         $item explode("."$server);
  20.         try {
  21.             $subDomain $item[0];
  22.         } catch (\Exception $e) {
  23.             echo $e->getMessage() . 'The subdomain parameters is required in the URL';
  24.         }
  25.         // Testing tenant
  26.         try {
  27.             $tenantData $this->defaultManager->getRepository(Tenant::class)->findOneBy([
  28.                 'subDomain' => $subDomain
  29.             ]);
  30.         } catch (\Exception $e) {
  31.             echo $e->getMessage() . 'The tenant for this ID not found';
  32.         }
  33.         $connection $this->event->getConnection('tenant');
  34.         if (!is_null($tenantData)) {
  35.             $connection->changeParams($tenantData->getDbName(), $tenantData->getDbUser(), $tenantData->getDbPassword());
  36.             $connection->reconnect();
  37.         }
  38.     }
  39. }