59 lines
1.6 KiB
PHP
59 lines
1.6 KiB
PHP
<?php
|
|
namespace App\Alias;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
|
|
class RemoteConnection
|
|
{
|
|
public function __construct(protected int $retries = 5)
|
|
{
|
|
$this->host = $_ENV['REMOTE_HOST'];
|
|
$this->database = $_ENV['REMOTE_DATABASE'];
|
|
$this->username = $_ENV['REMOTE_USER'];
|
|
$this->password = $_ENV['REMOTE_PASSWORD'];
|
|
if (isset($_ENV['REMOTE_PORT'])) {
|
|
$this->port = $_ENV['REMOTE_PORT'];
|
|
}
|
|
}
|
|
|
|
protected string $host;
|
|
protected string $database;
|
|
protected int $port;
|
|
protected string $username;
|
|
protected string $password;
|
|
|
|
protected PDO $connection;
|
|
public function connect(): PDO
|
|
{
|
|
if (!isset($this->connection)) {
|
|
$r = 0;
|
|
$exception = null;
|
|
while ($r < $this->retries) {
|
|
try {
|
|
$dsn = $this->getDsn();
|
|
$this->connection = new PDO($dsn, $this->username, $this->password);
|
|
} catch (PDOException $e) {
|
|
if ($exception !== null) {
|
|
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
|
|
}
|
|
$exception = $e;
|
|
usleep(500);
|
|
}
|
|
$r ++;
|
|
}
|
|
throw $exception;
|
|
}
|
|
return $this->connection;
|
|
}
|
|
|
|
protected function getDsn(): string
|
|
{
|
|
$dsn = "mysql:host={$this->host};dbname={$this->database}";
|
|
if (isset($this->port)) {
|
|
$dsn .= ";port={$this->port}";
|
|
}
|
|
return $dsn;
|
|
}
|
|
}
|