diff --git a/composer.json b/composer.json index a98ea01..cea605e 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ } }, "require": { - "doctrine/dbal": "^2.5.2" + "doctrine/dbal": "^2.5.2", + "psr/cache": "^1.0.0" }, "require-dev": { "behat/behat": "~3.0" diff --git a/src/Driver/MasterSlavesDriver.php b/src/Driver/MasterSlavesDriver.php index f80ca3e..0c34a1c 100644 --- a/src/Driver/MasterSlavesDriver.php +++ b/src/Driver/MasterSlavesDriver.php @@ -19,13 +19,52 @@ trait MasterSlavesDriver * @return \Doctrine\DBAL\Driver\Connection The database connection. */ public function connect(Array $params, $username = null, $password = null, Array $driverOptions = []) { + $cache = array_key_exists("config_cache", $driverOptions) ? $driverOptions["config_cache"] : null; + + $configParams = array_intersect_key($params, array_flip(["master", "slaves"])); + $key = "dblinker.master-slave-config.".hash("sha256", serialize($configParams)); + + $config = null; + if ($cache !== null) { + assert($driverOptions["config_cache"] instanceof \Psr\Cache\CacheItemPoolInterface); + $cacheItem = $cache->getItem($key); + $config = $cacheItem->get(); + } + + if ($config === null) { + $config = $this->config($configParams, $driverOptions); + } + + if ($cache !== null) { + $cacheItem->set($config); + $cache->save($cacheItem); + } + + return new MasterSlavesConnection($config["master"], $config["slaves"]); + } + + private function config(array $params, array $driverOptions) + { $driverKey = array_key_exists('driverClass', $params['master']) ? 'driverClass' : 'driver'; + $driverValue = $params['master'][$driverKey]; + $slaves = []; foreach ($params['slaves'] as $slaveParams) { $slaveParams[$driverKey] = $driverValue; $slaves[] = $slaveParams; } - return new MasterSlavesConnection($params['master'], $slaves); + + $config = [ + "master" => $params["master"], + "slaves" => $slaves, + ]; + + if (!array_key_exists("config_transform", $driverOptions)) { + return $config; + } + + assert(is_callable($driverOptions["config_transform"])); + return $driverOptions["config_transform"]($config); } }