76 lines
2.1 KiB
PHP
76 lines
2.1 KiB
PHP
<?php
|
|
namespace ProVM\Database;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use ProVM\Concept\Database;
|
|
use ProVM\Concept\Database\Connection as ConnectionInterface;
|
|
use ProVM\Concept\Database\ResultSet as ResultSetInterface;
|
|
use ProVM\Concept\Database\Transaction as TransactionInterface;
|
|
|
|
class Connection implements ConnectionInterface
|
|
{
|
|
public function __construct(Database $database)
|
|
{
|
|
$this->setDatabase($database);
|
|
$this->connect();
|
|
}
|
|
|
|
protected Database $database;
|
|
public function setDatabase(Database $database): ConnectionInterface
|
|
{
|
|
$this->database = $database;
|
|
return $this;
|
|
}
|
|
public function getDatabase(): Database
|
|
{
|
|
return $this->database;
|
|
}
|
|
public function connect(): ConnectionInterface
|
|
{
|
|
if (!isset($this->pdo)) {
|
|
if ($this->getDatabase()->needsUser()) {
|
|
$pdo = new PDO($this->getDatabase()->getDSN(), $this->getDatabase()->getUsername(), $this->getDatabase()->getPassword());
|
|
} else {
|
|
$pdo = new PDO($this->getDatabase()->getDSN());
|
|
}
|
|
$this->setPDO($pdo);
|
|
}
|
|
return $this;
|
|
}
|
|
protected PDO $pdo;
|
|
public function setPDO(PDO $pdo): ConnectionInterface
|
|
{
|
|
$this->pdo = $pdo;
|
|
return $this;
|
|
}
|
|
public function getPDO(): PDO
|
|
{
|
|
return $this->pdo;
|
|
}
|
|
public function query(string $query): ResultSetInterface
|
|
{
|
|
$st = $this->getPDO()->query($query);
|
|
if (!$st) {
|
|
throw new PDOException("Could not run query {$query}");
|
|
}
|
|
return new ResultSet($st);
|
|
}
|
|
public function prepare(string $query): ResultSetInterface
|
|
{
|
|
$st = $this->getPDO()->prepare($query);
|
|
if (!$st) {
|
|
throw new PDOException("Could not prepare query {$query}");
|
|
}
|
|
return new ResultSet($st);
|
|
}
|
|
public function execute(string $query, array $values): ResultSetInterface
|
|
{
|
|
return $this->prepare($query)->execute($values);
|
|
}
|
|
public function transaction(): TransactionInterface
|
|
{
|
|
return new Transaction($this->getPDO());
|
|
}
|
|
}
|