Skip to content

Commit

Permalink
Pass configurations to connections
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonOkulov committed Nov 19, 2019
1 parent 0119327 commit 07d82d2
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions src/Phact/Orm/ConnectionManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand All @@ -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
{
Expand All @@ -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}'");
}
}

0 comments on commit 07d82d2

Please sign in to comment.