ringfinger/backend/classes/core/Table.php

293 lines
6.3 KiB
PHP
Raw Permalink Normal View History

2020-08-17 23:46:58 +02:00
<?php
/**
* Basic object to load a mysql table inside an object.
*/
abstract class Table
{
public const TYPE_STRING = 1;
public const TYPE_INTEGER = 2;
public const TYPE_FLOAT = 3;
public const TYPE_DATETIME = 4;
public const TYPE_BOOL = 5;
protected const VALUE = 'value';
protected const TYPE = 'type';
protected ?DatabaseInterface $database;
protected string $tableName;
protected array $fields;
protected string $primaryKey;
2020-08-23 12:37:39 +02:00
protected bool $isPrimKeyManual = false;
2020-08-17 23:46:58 +02:00
public function __construct(string $tableName, $id, ?DatabaseInterface & $database)
{
$this->tableName = $tableName;
$this->fields = [];
2020-08-23 12:37:39 +02:00
$this->database = $database;
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$this->database->Query(sprintf('DESCRIBE %s', $tableName));
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$result = $this->database->getResult();
2020-08-17 23:46:58 +02:00
foreach ($result as $field) {
2020-08-23 12:37:39 +02:00
$sqlType = substr_count(
$field['Type'], '(') === 0 ? $field['Type'] : strstr($field['Type'],
'(',
true
);
2020-08-17 23:46:58 +02:00
switch ($sqlType) {
case 'varchar':
case 'char':
case 'text':
case 'longtext':
case 'mediumtext':
case 'tinytext':
$type = self::TYPE_STRING;
break;
case 'int':
case 'smallint':
case 'mediumint':
case 'bigint':
$type = self::TYPE_INTEGER;
break;
case 'float':
case 'decimal':
case 'double':
case 'real':
$type = self::TYPE_FLOAT;
break;
case 'datetime':
2020-08-23 12:37:39 +02:00
case 'date':
2020-08-17 23:46:58 +02:00
$type = self::TYPE_DATETIME;
break;
2020-08-23 12:37:39 +02:00
case 'tinyint':
$type = self::TYPE_BOOL;
break;
2020-08-17 23:46:58 +02:00
default:
2020-08-21 22:46:19 +02:00
throw new DatabaseException(
sprintf('Type %s of field %s couldn\'t be handled', $sqlType, $field['Field']),
ServerStatus::INTERNAL_ERROR
);
2020-08-17 23:46:58 +02:00
}
2020-08-23 12:37:39 +02:00
$this->addField($field['Field'], $type);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
if ($field['Key'] === 'PRI') {
2020-08-17 23:46:58 +02:00
$this->primaryKey = $field['Field'];
}
}
if (!$this->isPrimKeyManual && $id !== null) {
2020-08-23 12:37:39 +02:00
$this->loadById($id);
}
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function getPrimaryKey()
{
if ($this->primaryKey === null) {
return null;
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return $this->getField($this->primaryKey);
}
2020-08-17 23:46:58 +02:00
protected function addField(string $name, int $type): void
{
if (!self::IsValidType($type)) {
2020-08-21 22:46:19 +02:00
throw new DatabaseException(
2020-08-23 12:37:39 +02:00
sprintf('Field %s has invalid type of %s!', $name, $type),
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
}
$this->fields[$name] = [self::VALUE => null, self::TYPE => $type];
}
2020-08-23 12:37:39 +02:00
protected function loadById($id): void
2020-08-17 23:46:58 +02:00
{
2020-08-21 22:46:19 +02:00
$this->database->Query(
sprintf('SELECT * FROM %s WHERE %s = :id', $this->tableName, $this->primaryKey),
['id' => $id]
);
2020-08-17 23:46:58 +02:00
$result = $this->database->getResult();
if (count($result) === 0) {
2020-08-21 22:46:19 +02:00
throw new DatabaseException(
sprintf('No %s with id %d found!', $this->tableName, $id),
ServerStatus::BAD_REQUEST
);
2020-08-17 23:46:58 +02:00
}
foreach ($result[0] as $field => $value) {
$this->setField($field, $value);
}
}
public function Flush(): void
2020-08-23 12:37:39 +02:00
{
$this->database->Delete($this->tableName, []);
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function Delete(): void
{
2020-08-21 22:46:19 +02:00
$this->database->Delete($this->tableName, [$this->primaryKey => $this->getPrimaryKey()]);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
foreach ($this->GetAllFieldNames() as $field) {
$this->fields[$field][self::VALUE] = null;
}
}
2020-08-17 23:46:58 +02:00
protected function getField(string $name)
{
if (!array_key_exists($name, $this->fields)) {
return null;
}
return $this->fields[$name][self::VALUE];
}
2020-08-23 12:37:39 +02:00
/**
* Sets the value for the given field inside the database.
*/
2020-08-17 23:46:58 +02:00
protected function setField(string $name, $value): void
{
if (!$this->HasField($name)) {
2020-08-21 22:46:19 +02:00
throw new DatabaseException(
sprintf('Field %s doesn\'t exist!', $name),
ServerStatus::INTERNAL_ERROR
);
2020-08-17 23:46:58 +02:00
}
if ($value === null) {
$this->fields[$name][self::VALUE] = null;
return;
}
switch ($this->fields[$name][self::TYPE]) {
case self::TYPE_STRING:
$this->fields[$name][self::VALUE] = (string)$value;
return;
case self::TYPE_INTEGER:
$this->fields[$name][self::VALUE] = (int)$value;
return;
case self::TYPE_FLOAT:
$this->fields[$name][self::VALUE] = (float)$value;
return;
case self::TYPE_DATETIME:
try {
2020-08-23 12:37:39 +02:00
$this->fields[$name][self::VALUE] = new DateTime((string)$value);
} 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
return;
2020-08-23 12:37:39 +02:00
case self::TYPE_BOOL:
$this->fields[$name][self::VALUE] = (bool)$value;
2020-08-17 23:46:58 +02:00
}
}
/**
2020-08-23 12:37:39 +02:00
* Checks if the table has the given column.
2020-08-17 23:46:58 +02:00
*/
public function HasField(string $name): bool
{
return array_key_exists($name, $this->fields);
}
2020-08-23 12:37:39 +02:00
/**
* Saves the whole object into the database.
*/
2020-08-17 23:46:58 +02:00
public function Save(): void
{
$fields = [];
foreach ($this->GetAllFieldNames() as $fieldName) {
2020-08-23 12:37:39 +02:00
$field = $this->getField($fieldName);
if ($field instanceof DateTime) {
$fields[$fieldName] = $field->format('Y-m-d H:i:s');
} else if (is_bool($field)) {
$fields[$fieldName] = (int)$field;
} else {
$fields[$fieldName] = $field;
}
2020-08-17 23:46:58 +02:00
}
if ($this->isPrimKeyManual) {
2020-08-23 12:37:39 +02:00
$this->saveWithManualId($fields);
} else {
$this->saveWithPrimaryKey($fields);
}
2020-08-17 23:46:58 +02:00
}
/**
* @return string[]
*/
public function GetAllFieldNames(): array
{
$fieldNames = [];
foreach ($this->fields as $name => $field) {
$fieldNames[] = $name;
}
return $fieldNames;
}
2020-08-23 12:37:39 +02:00
/**
* Checks if the index is a valid backend type.
*/
2020-08-17 23:46:58 +02:00
public static function IsValidType(int $type): bool
{
$validTypes = [
self::TYPE_STRING,
self::TYPE_INTEGER,
self::TYPE_FLOAT,
self::TYPE_DATETIME,
2020-08-23 12:37:39 +02:00
self::TYPE_BOOL,
2020-08-17 23:46:58 +02:00
];
return in_array($type, $validTypes);
}
protected function saveWithManualId(array $fields): void
2020-08-23 12:37:39 +02:00
{
if ($this->getField($this->primaryKey) === null) {
throw new DatabaseException(
'Manual primary key must not be null!',
2020-08-21 22:46:19 +02:00
ServerStatus::INTERNAL_ERROR
);
2020-08-23 12:37:39 +02:00
}
$hasKey = (bool)$this->database->Count(
$this->tableName,
[$this->primaryKey => $this->getField($this->primaryKey)]
);
if ($hasKey) {
$this->database->Update(
$this->tableName, $fields, [$this->primaryKey => $this->getField($this->primaryKey)]
);
} else {
$this->database->Insert($this->tableName, $fields);
}
}
protected function saveWithPrimaryKey(array $fields): void
{
if ($this->getField($this->primaryKey) !== null) {
$this->database->Update(
$this->tableName, $fields, [$this->primaryKey => $this->getField($this->primaryKey)]
);
} else {
$this->setField($this->primaryKey, $this->database->Insert($this->tableName, $fields));
}
}
2020-08-17 23:46:58 +02:00
}