Last active
June 11, 2016 03:18
-
-
Save texdc/972b9b583369bf36b070 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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