game/_incl_data/class/DarksLight2/Entity.php

122 lines
2.9 KiB
PHP

<?php
namespace DarksLight2;
use Core\Db;
use Exception;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
abstract class Entity
{
protected string $table;
public function toSnakCase($string): string
{
return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $string));
}
protected function getTable(): string
{
if(!isset($this->table)) {
try {
$class = new ReflectionClass($this);
$table_name = preg_replace(
'/_entity/',
'',
$this->toSnakCase($class->getShortName())
);
if (!Db::getRow("SHOW TABLES LIKE '$table_name'")) {
throw new Exception(
'Undefined table ' . $table_name . ' in database'
);
}
$this->table = $table_name;
} catch (Exception $e) {
die;
}
}
return $this->table;
}
public function morph(array $object) {
$class = new ReflectionClass(get_called_class());
try {
$entity = $class->newInstance();
} catch (ReflectionException $e) {
die($e->getMessage());
}
foreach($class->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) {
if (isset($object[$prop->getName()])) {
$prop->setValue($entity,$object[$prop->getName()]);
}
}
return $entity;
}
public function find(array $condition): ?Entity
{
$query = "SELECT * FROM {$this->getTable()} WHERE ";
$values = [];
foreach ($condition as $field => $value) {
$values[] = $value;
$query .= "$field = ?";
}
$request = Db::prepare("$query LIMIT 1");
$request->execute($values);
if($result = $request->fetch()) {
return self::morph($result);
}
return null;
}
/**
* @param array|null $condition
*
* @return Entity[]|null
*/
public function findAll(?array $condition = null): ?array
{
if(!isset($condition)) {
$query = "SELECT * FROM {$this->getTable()}";
} else {
$query = "SELECT * FROM {$this->getTable()} WHERE ";
$values = [];
foreach ($condition as $field => $value) {
$values[] = $value;
$query .= "$field = ?";
}
}
$request = Db::prepare("$query");
$request->execute($values ?? null);
if($rows = $request->fetchAll()) {
$result = [];
foreach ($rows as $row) {
$result[] = self::morph($row);
}
return $result;
}
return null;
}
public function save(): void
{
}
}