ringfinger/backend/classes/core/MySqlDatabase.php

282 lines
5.9 KiB
PHP
Raw Permalink Normal View History

2020-08-17 23:46:58 +02:00
<?php
declare(strict_types=1);
2020-08-18 11:46:03 +02:00
final class MySqlDatabase implements DatabaseInterface
2020-08-17 23:46:58 +02:00
{
private const CHARS_ALLOWED_IN_TABLE_NAMES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-';
private ?PDO $connection;
private ?PDOStatement $cursor;
2020-08-23 12:37:39 +02:00
private bool $isTransactionOpen = false;
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function __construct(
2020-08-17 23:46:58 +02:00
string $hostname = Setting::MYSQL_HOST,
string $user = Setting::MYSQL_USER,
string $password = Setting::MYSQL_PASSWORD,
string $database = Setting::MYSQL_DATABASE
) {
2020-08-23 12:37:39 +02:00
try {
$this->connection = new PDO("mysql:host=$hostname;dbname=$database", $user, $password);
} catch (Throwable $e) {
throw new DatabaseException(
'Couldn\'t connect to the database!',
2020-08-21 22:46:19 +02:00
ServerStatus::INTERNAL_ERROR
);
2020-08-23 12:37:39 +02:00
}
2020-08-17 23:46:58 +02:00
}
public function __destruct()
{
$this->connection = null;
}
public function Query(string $query, array $params = []): void
{
$this->cursor = $this->connection->prepare($query);
if (!$this->cursor) {
2020-08-19 21:06:45 +02:00
throw new DatabaseException(
2020-08-23 12:37:39 +02:00
'Initialization of database cursor failed',
DatabaseException::CONNECTION_FAILED
);
2020-08-17 23:46:58 +02:00
}
foreach ($params as $key => $param) {
2020-08-23 12:37:39 +02:00
if (is_bool($param)) {
$param = (int)$param;
}
2020-08-17 23:46:58 +02:00
$this->cursor->bindValue(':' . $key, $param);
}
if (!$this->cursor->execute()) {
2020-08-23 12:37:39 +02:00
throw new DatabaseException($this->cursor->errorInfo()[2], $this->cursor->errorInfo()[1]);
}
2020-08-17 23:46:58 +02:00
}
public function getResult(): array
{
$result = [];
while ($fetch = $this->cursor->fetchObject()) {
$row = [];
foreach (get_object_vars($fetch) as $key => $value) {
$row[$key] = $value;
}
$result[] = $row;
}
return $result;
}
2020-08-23 12:37:39 +02:00
/**
* Selects backend from a table.
*/
public function Select(
2020-08-17 23:46:58 +02:00
string $tableName,
array $fields = [],
array $conditions = [],
int $limit = 0,
array $orderBy = [],
bool $asc = true,
2020-08-23 12:37:39 +02:00
int $offset = 0
2020-08-17 23:46:58 +02:00
): array {
if (!self::isValidTableName($tableName)) {
[];
}
if (count($fields) === 0) {
$fieldsExpression = '*';
} else {
$fieldsExpression = implode(',', $fields);
}
$conditionsExpression = '';
$conditionPairs = [];
foreach ($conditions as $field => $value) {
$conditionPairs[] = sprintf('%s = :%s ', $field, $field);
}
if (count($conditions) > 0) {
$conditionsExpression = 'WHERE ';
$conditionsExpression .= implode(' AND ', $conditionPairs);
}
$orderStatement = '';
if (count($orderBy) > 0) {
$orderStatement = 'ORDER BY ' . implode(',', $orderBy);
if (!$asc) {
$orderStatement .= ' DESC';
}
}
$limitStatement = '';
if ($limit > 0) {
$limitStatement = 'LIMIT ' . $limit;
}
$offsetStatement = '';
if ($offset > 0) {
2020-08-23 12:37:39 +02:00
$offsetStatement = 'OFFSET ' . $offset;
}
2020-08-17 23:46:58 +02:00
$query = sprintf(
'SELECT %s FROM %s %s %s %s %s',
$fieldsExpression,
$tableName,
$conditionsExpression,
$orderStatement,
$limitStatement,
2020-08-23 12:37:39 +02:00
$offsetStatement
2020-08-17 23:46:58 +02:00
);
2020-08-23 12:37:39 +02:00
try {
$this->Query($query, $conditions);
} catch (Throwable $e) {
throw new DatabaseException(
$e->getMessage(),
2020-08-21 22:46:19 +02:00
ServerStatus::INTERNAL_ERROR
);
2020-08-23 12:37:39 +02:00
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return $this->getResult();
2020-08-17 23:46:58 +02:00
}
2020-08-23 12:37:39 +02:00
/**
* Deletes rows from a table.
*/
public function Delete(string $table, array $conditions): void
{
if (count($conditions) === 0) {
$conditionsStatement = '1';
} else {
$conditionPairs = [];
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
foreach ($conditions as $field => $value) {
$conditionPairs[] = sprintf('%s=:Condition%s', $field, $field);
$conditions['Condition' . $field] = $value;
unset($conditions[$field]);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$conditionsStatement = implode(' AND ', $conditionPairs);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$query = sprintf('DELETE FROM %s WHERE %s', $table, $conditionsStatement);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$this->Query($query, $conditions);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function Insert(string $table, array $fields): ?int
{
if (count($fields) === 0) {
throw new DatabaseException('Row to insert is empty!');
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$fieldNames = implode(',', array_keys($fields));
$fieldPlaceholder = [];
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
foreach ($fields as $name => $value) {
$fieldPlaceholder[] = ':' . $name;
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$query = sprintf(
'INSERT INTO %s (%s) VALUES (%s)', $table, $fieldNames, implode(',', $fieldPlaceholder)
);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$this->Query($query, $fields);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$lastInsertedId = $this->GetLastInsertedId();
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
if ((int)$lastInsertedId === 0) {
return null;
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return $lastInsertedId;
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function Update(string $table, array $fields, array $conditions): void
{
$conditionPairs = [];
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
foreach ($conditions as $field => $value) {
$conditionPairs[] = sprintf('%s=:Condition%s', $field, $field);
$conditions['Condition' . $field] = $value;
unset($conditions[$field]);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$conditionsStatement = implode(' AND ', $conditionPairs);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$fieldPairs = [];
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
foreach ($fields as $field => $value) {
$fieldPairs[] = sprintf('%s=:%s', $field, $field);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$fieldsStatement = implode(',', $fieldPairs);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$query = sprintf('UPDATE %s SET %s WHERE %s', $table, $fieldsStatement, $conditionsStatement);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$this->Query($query, array_merge($fields, $conditions));
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function Count(string $table, array $conditions = []): int
{
$result = $this->Select($table, ['count(*)'], $conditions);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return (int)$result[0]['count(*)'];
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function hasTransaction(): bool
{
return $this->isTransactionOpen;
}
2020-08-18 11:46:03 +02:00
2020-08-23 12:37:39 +02:00
public function startTransaction(): void
{
$this->connection->beginTransaction();
$this->isTransactionOpen = true;
}
2020-08-18 11:46:03 +02:00
2020-08-23 12:37:39 +02:00
public function rollback(): void
{
$this->connection->rollBack();
$this->isTransactionOpen = false;
}
2020-08-18 11:46:03 +02:00
2020-08-23 12:37:39 +02:00
public function commit(): void
{
$this->connection->commit();
$this->isTransactionOpen = false;
}
2020-08-18 11:46:03 +02:00
2020-08-23 12:37:39 +02:00
public function GetLastInsertedId(): int
{
$this->Query('SELECT LAST_INSERT_ID() as ID');
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return (int)$this->getResult()[0]['ID'];
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
/**
* Does a check if the given table name contains forbidden chars.
*/
2020-08-17 23:46:58 +02:00
private static function isValidTableName(string $tableName): bool
{
foreach (str_split($tableName) as $char) {
if (substr_count(self::CHARS_ALLOWED_IN_TABLE_NAMES, $char) === 0) {
return false;
}
}
return true;
}
}