Skip to content

Commit

Permalink
Merge pull request #38 from mathroc/feature/master-slaves-config-cach…
Browse files Browse the repository at this point in the history
…e-and-transform

makes it possible to transform master slaves config and keep it cached
  • Loading branch information
mathroc authored Nov 3, 2016
2 parents bdf788e + dbd5c78 commit 88999be
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
41 changes: 40 additions & 1 deletion src/Driver/MasterSlavesDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 88999be

Please sign in to comment.