2023-07-24 20:55:26 -04:00
|
|
|
<?php
|
|
|
|
namespace Incoviba\Common\Implement;
|
|
|
|
|
|
|
|
use PDO;
|
|
|
|
use PDOStatement;
|
|
|
|
use PDOException;
|
|
|
|
use Incoviba\Common\Define;
|
|
|
|
|
|
|
|
class Connection implements Define\Connection
|
|
|
|
{
|
2023-11-22 19:08:19 -03:00
|
|
|
public function __construct(protected Define\Database $database, protected Database\Query\Builder $queryBuilder) {}
|
2023-07-24 20:55:26 -04:00
|
|
|
|
|
|
|
protected PDO $connection;
|
|
|
|
public function connect(): Define\Connection
|
|
|
|
{
|
|
|
|
if (!isset($this->connection)) {
|
|
|
|
if ($this->database->needsUser()) {
|
|
|
|
$this->connection = new PDO($this->database->getDSN(), $this->database->user, $this->database->password);
|
|
|
|
} else {
|
|
|
|
$this->connection = new PDO($this->database->getDSN());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
public function getPDO(): PDO
|
|
|
|
{
|
|
|
|
$this->connect();
|
|
|
|
return $this->connection;
|
|
|
|
}
|
2023-11-22 19:08:19 -03:00
|
|
|
public function getQueryBuilder(): Database\Query\Builder
|
|
|
|
{
|
|
|
|
return $this->queryBuilder;
|
|
|
|
}
|
2023-07-24 20:55:26 -04:00
|
|
|
|
|
|
|
public function query(string $query): PDOStatement
|
|
|
|
{
|
|
|
|
$this->connect();
|
|
|
|
$statement = $this->connection->query($query);
|
|
|
|
if ($statement === false) {
|
|
|
|
throw new PDOException("Query failed: '{$query}'");
|
|
|
|
}
|
|
|
|
return $statement;
|
|
|
|
}
|
|
|
|
public function prepare(string $query): PDOStatement
|
|
|
|
{
|
|
|
|
$this->connect();
|
|
|
|
$statement = $this->connection->prepare($query);
|
|
|
|
if ($statement === false) {
|
|
|
|
throw new PDOException("Query failed: '{$query}'");
|
|
|
|
}
|
|
|
|
return $statement;
|
|
|
|
}
|
|
|
|
public function execute(string $query, ?array $data = null): PDOStatement
|
|
|
|
{
|
|
|
|
if ($data === null) {
|
|
|
|
return $this->query($query);
|
|
|
|
}
|
|
|
|
$statement = $this->prepare($query);
|
|
|
|
$status = $statement->execute($data);
|
|
|
|
if ($status === false) {
|
|
|
|
throw new PDOException("Query could not be executed: '{$query}'");
|
|
|
|
}
|
|
|
|
return $statement;
|
|
|
|
}
|
|
|
|
}
|