From 07d82d22539525b42aaca8bb22bd01ead9cdd5c1 Mon Sep 17 00:00:00 2001 From: Anton Okulov Date: Tue, 19 Nov 2019 10:03:36 +0300 Subject: [PATCH] Pass configurations to connections --- src/Phact/Orm/ConnectionManager.php | 47 +++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/Phact/Orm/ConnectionManager.php b/src/Phact/Orm/ConnectionManager.php index 67ac778..4038856 100644 --- a/src/Phact/Orm/ConnectionManager.php +++ b/src/Phact/Orm/ConnectionManager.php @@ -15,6 +15,10 @@ use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; +use Phact\Di\Container; +use Phact\Di\ContainerInterface; +use Phact\Exceptions\DependencyException; +use Phact\Exceptions\InvalidConfigException; use Phact\Exceptions\UnknownPropertyException; use Phact\Helpers\SmartProperties; @@ -27,6 +31,16 @@ class ConnectionManager implements ConnectionManagerInterface public $defaultConnection = 'default'; + /** + * @var ContainerInterface|null + */ + private $container; + + public function __construct(ContainerInterface $container = null) + { + $this->container = $container; + } + public function getDefaultConnection(): string { return $this->defaultConnection; @@ -42,6 +56,8 @@ public function setConnections($config = []) * @return \Doctrine\DBAL\Connection * @throws UnknownPropertyException * @throws \Doctrine\DBAL\DBALException + * @throws InvalidConfigException + * @throws DependencyException */ public function getConnection($name = null): Connection { @@ -50,14 +66,39 @@ public function getConnection($name = null): Connection } if (!isset($this->_connections[$name])) { if (isset($this->_connectionsConfig[$name])) { - $config = $this->_connectionsConfig[$name]; + $params = $this->_connectionsConfig[$name]; + + $configuration = new Configuration(); + if (isset($params['configuration'])) { + $configuration = $this->retrieveConfiguration($params['configuration']); + unset($params['configuration']); + } + /** @var Connection $connection */ - $connection = DriverManager::getConnection($config, new Configuration()); + $connection = DriverManager::getConnection($params, $configuration); $this->_connections[$name] = $connection; } else { - throw new UnknownPropertyException("Connection with name " . $name . " not found"); + throw new UnknownPropertyException("Connection with name '{$name}' not found"); } } return $this->_connections[$name]; } + + /** + * @param $name + * @return Configuration + * @throws InvalidConfigException + * @throws DependencyException + */ + public function retrieveConfiguration($name): Configuration + { + if (!$this->container) { + throw new DependencyException(sprintf('Dependency %s is not loaded', Container::class)); + } + $name = ltrim($name, '@'); + if ($this->container->has($name)) { + return $this->container->get($name); + } + throw new InvalidConfigException("Count not find connection configuration by name '{$name}'"); + } } \ No newline at end of file