2022-06-17 20:53:35 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Objects\DatabaseEntity;
|
|
|
|
|
|
|
|
use Driver\SQL\Condition\Condition;
|
|
|
|
use Driver\SQL\SQL;
|
|
|
|
|
|
|
|
abstract class DatabaseEntity {
|
|
|
|
|
|
|
|
private static array $handlers = [];
|
|
|
|
private ?int $id;
|
|
|
|
|
|
|
|
public function __construct() {
|
|
|
|
$this->id = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function find(SQL $sql, int $id): ?DatabaseEntity {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler = self::getHandler($sql);
|
|
|
|
return $handler->fetchOne($id);
|
2022-06-17 20:53:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function findAll(SQL $sql, ?Condition $condition): ?array {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler = self::getHandler($sql);
|
|
|
|
return $handler->fetchMultiple($condition);
|
2022-06-17 20:53:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function save(SQL $sql): bool {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler = self::getHandler($sql);
|
|
|
|
$res = $handler->insertOrUpdate($this);
|
2022-06-17 20:53:35 +02:00
|
|
|
if ($res === false) {
|
|
|
|
return false;
|
|
|
|
} else if ($this->id === null) {
|
|
|
|
$this->id = $res;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function delete(SQL $sql): bool {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler = self::getHandler($sql);
|
2022-06-17 20:53:35 +02:00
|
|
|
if ($this->id === null) {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler->getLogger()->error("Cannot delete entity without id");
|
2022-06-17 20:53:35 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-06-17 22:58:42 +02:00
|
|
|
return $handler->delete($this->id);
|
2022-06-17 20:53:35 +02:00
|
|
|
}
|
|
|
|
|
2022-06-17 22:58:42 +02:00
|
|
|
public static function getHandler(SQL $sql, $obj_or_class = null): DatabaseEntityHandler {
|
2022-06-17 20:53:35 +02:00
|
|
|
|
|
|
|
if (!$obj_or_class) {
|
|
|
|
$obj_or_class = get_called_class();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!($obj_or_class instanceof \ReflectionClass)) {
|
|
|
|
$class = new \ReflectionClass($obj_or_class);
|
|
|
|
} else {
|
|
|
|
$class = $obj_or_class;
|
|
|
|
}
|
|
|
|
|
|
|
|
$handler = self::$handlers[$class->getShortName()] ?? null;
|
|
|
|
if (!$handler) {
|
2022-06-17 22:58:42 +02:00
|
|
|
$handler = new DatabaseEntityHandler($sql, $class);
|
2022-06-17 20:53:35 +02:00
|
|
|
self::$handlers[$class->getShortName()] = $handler;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $handler;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getId(): ?int {
|
|
|
|
return $this->id;
|
|
|
|
}
|
|
|
|
}
|