42 lines
1.2 KiB
PHP
42 lines
1.2 KiB
PHP
<?php
|
|
namespace ProVM\Service;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
class Connector
|
|
{
|
|
public function __construct(protected string $host, protected string $name, protected string $username, protected string $password, protected string $retries, protected LoggerInterface $logger) {}
|
|
|
|
protected PDO $connection;
|
|
|
|
/**
|
|
* @throws PDOException
|
|
*/
|
|
public function connect(): PDO
|
|
{
|
|
if (!isset($this->connection)) {
|
|
$this->logger->debug('Connecting');
|
|
$r = 0;
|
|
$exception = null;
|
|
while($r < $this->retries) {
|
|
try {
|
|
$dsn = "mysql:host={$this->host};dbname={$this->name}";
|
|
$this->connection = new PDO($dsn, $this->username, $this->password);
|
|
return $this->connection;
|
|
} catch (PDOException $e) {
|
|
$this->logger->debug('Retrying');
|
|
if ($exception !== null) {
|
|
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
|
|
}
|
|
$exception = $e;
|
|
}
|
|
$r ++;
|
|
}
|
|
throw $exception;
|
|
}
|
|
return $this->connection;
|
|
}
|
|
}
|