Skip to content

Instantly share code, notes, and snippets.

@texdc
Last active June 11, 2016 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save texdc/972b9b583369bf36b070 to your computer and use it in GitHub Desktop.
Save texdc/972b9b583369bf36b070 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
class CallbackIterator implements Iterator
{
private $index = 0;
private $maxIterations = 0;
private $callback;
public function __construct(int $anIterationCount, callable $aCallback)
{
$this->maxIterations = abs($anIterationCount);
$this->callback = $aCallback;
}
public function current()
{
return $this->callback();
}
public function next()
{
++$this->index;
}
public function key() : int
{
return $this->index;
}
public function valid() : bool
{
return $this->maxIterations > $this->index;
}
public function rewind()
{
$this->index = 0;
}
}
<?php declare(strict_types=1);
$connection = null;
$instanceId = $configuration->getProperty("db.master.instanceId");
$dsn = buildDsn(
$configuration->getProperty("db.master.database"),
$endpointManager->getEndpoint($instanceId)
);
$iterator = new CallbackIterator(5, function() use ($dsn, $connectionManager) {
return $connectionManager->connect($dsn);
});
while ($connection === null && $iterator->valid()) {
try {
$log->debug("Connecting [$instanceId]");
$connection = $iterator->current();
} catch (ConnectionException $ce) {
$log->debug("Failed to connect [$instanceId]");
$log->error($ce->getMessage());
$log->error($ce->getTraceAsString());
}
$iterator->next();
}
if ($connection === null) {
throw ConnectionException::failure($instanceId);
}
function buildDsn(string $aDatabaseName, Endpoint $anEndpoint) : string
{
$cdn = ($anEndpoint->hasReplicas()) ? buildReplicaDsn($anEndpoint) : buildEndpointDsn($anEndpoint);
$cdn .= "/" . $aDatabaseName;
return $cdn;
}
function buildEndpointDsn(Endpoint $anEndpoint) : string
{
return "mysql://" . $anEndpoint->getUri();
}
function buildReplicaDsn(Endpoint $anEndpoint) : string
{
$cdn = "mysql:replication://" . $anEndpoint->getUri();
/** @var $replica Endpoint */
foreach ($anEndpoint->getReplicas() as $replica) {
$cdn .= "," . $replica->getUri();
}
return $cdn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment