<?phpnamespace App\Extension\Doctrine\Connection;use Doctrine\DBAL\Connection;use Doctrine\DBAL\Event\ConnectionEventArgs;use Doctrine\DBAL\Events;use Symfony\Component\HttpFoundation\Session\Session;/** * @author Dawid zulus Pakula [zulus@w3des.net] */class ConnectionWrapper extends Connection{ const SESSION_ACTIVE_DYNAMIC_CONN = 'cliente_connection'; /** * @var Session */ private $session; /** * @var bool */ private $_isConnected = false; /** * @param Session $sess * @return void */ public function setSession(Session $sess) { $this->session = $sess; } /** * @param string $dbname * @param string|null $host * @return void */ public function forceSwitch(string $dbname, ?string $host = NULL) { if ( $this->session->has(self::SESSION_ACTIVE_DYNAMIC_CONN) ) { $session = $this->session->get(self::SESSION_ACTIVE_DYNAMIC_CONN); if ( $session['dbname'] === $dbname ) { return; } } $this->session->set(self::SESSION_ACTIVE_DYNAMIC_CONN, ['dbname'=>$dbname,'host'=>$host]); if ( $this->isConnected() ) { $this->close(); } } /** * {@inheritdoc} */ public function connect() { if ( !$this->session->has(self::SESSION_ACTIVE_DYNAMIC_CONN) ) { throw new \InvalidArgumentException('You have to inject into valid context first'); } if ( $this->isConnected() ) { return true; } $clienteParams = $this->session->get(self::SESSION_ACTIVE_DYNAMIC_CONN); $params = $this->getParams(); $params['dbname'] = $clienteParams['dbname']; if ( NULL !== $clienteParams['host'] ) { $params['host'] = $clienteParams['host']; } $this->_conn = $this->_driver->connect( $params ,$params['user'] ,$params['password'] ); if ( $this->_eventManager->hasListeners(Events::postConnect) ) { $eventArgs = new ConnectionEventArgs($this); $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs); } $this->_isConnected = true; return $this->_isConnected; } /** * {@inheritdoc} */ public function isConnected() { return $this->_isConnected; } /** * {@inheritdoc} */ public function close() { if ($this->isConnected()) { parent::close(); $this->_isConnected = false; } }}